강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

김범준님의 프로필 이미지
김범준

작성한 질문수

홍정모의 따라하며 배우는 C++

5.10 std::cin 더 잘 쓰기

제가 알고 있는게 맞는지 훈수좀요!!

작성

·

313

·

수정됨

0

ignore()함수는 cin연산자?? 의 구성요소 중 하나이고

 

cin은 std에 정리 되어 있으며 이 std는

 

iostream이라는 라이브러리(도서관)에 정의 되어 있다......!라고 하면 되는 건가요

 

그리고 ignore(x,y)는 x까지 입력을 받거나 y를 만나면 그 이후는 무시하라! 라고 이해하면 되는 거죠?

 

그리고 지금 드는 의문인데요 using namespace std;를 사용하고 있는데 ignore()이랑 fail()은 왜 앞에 std::cin을 붙여줘야 하죠?

답변 1

0

넵 :)

ignore과 fail의 경우에는..

std::를 붙여도 되고 떼도 됩니다.

아래 코드로 확인해보시겠어요?

#include <iostream>

using namespace std;

int getInt()
{
	cout << "Enter an integer number : ";
	int x;
	cin >> x;
	if (cin.fail()) 
	{
		cin.clear(); 
		cin.ignore(32767, '\n'); 
		cout << "Invaild number, please try again" << endl;
	}
	else
	{
		std::cin.ignore(32767, '\n');
		return x;
	}
}

char getOperator()
{
	cout << "Enter an operator (+,-) : ";
	char op;
	cin >> op;
	return op;
}
void printResult(int x, char op, int y)
{
	if (op == '+') cout << x + y << endl;
	else if (op == '-') cout << x - y << endl;
	else
	{
		cout << "Invalid operator" << endl;
	}
}

int main()
{
	int x = getInt(); 
	char op = getOperator(); 
	int y = getInt();

	printResult(x, op, y);

	return 0;
}
김범준님의 프로필 이미지
김범준
질문자

호오 확인했습니다 감사합니다!

김범준님의 프로필 이미지
김범준

작성한 질문수

질문하기