본문 바로가기
코딩/C++

입력받는 법

by sonysame 2024. 2. 22.

 

1. String 입력받는법

#include <iostream>
#include <string>
#include <limits>
using namespace std;

int main() {
	const char my_strs[] = "Hello, World";
	const string my_hello = "Hello, World";
	cout << my_strs << endl;
	cout << my_hello << endl;

	cout << "Your name ? : ";
	string name;
	cin >> name;
	//std::getline(std::cin, name);

	//std::cin.ignore(32767, '\n');
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

	cout << "Your age ? : ";
	string age;
	//cin >> age;
	std::getline(std::cin, age);
	cout << name << " " << age << endl;

}
  • cin >> age // 공백 혹은 개행문자 이전까지 읽음,  '\n'를 처리하지 않고 입력버퍼에 남겨둔다.
  • std::getline(std::cin,age) // 공백이 포함된 문자열을 읽고 싶을때, 구분자를 만날 때까지 입력을 받는다. 개행문자 전까지 입력을 받으나, \n을 버퍼에 남겨두지 않는다. 
  • std::cin.ignore(32767,\n) // 버퍼를 비움
  • cin 다음 입력을 cin으로 받을 경우에는, 전 버퍼에 있던 공백 및 개행문자를 무시하기 때문에 버퍼를 굳이 비워주지 않아도 된다.
  • cin 다음 입력을 getline으로 받을 경우에는, 전 버퍼에 있던 공백 및 개행문자를 포함해서 입력받기 때문에, 버퍼를 지워주는 작업이 필요하다.
  • getline 다음 입력을 getline으로 받을 경우, getline은 \n 문자를 버퍼에 포함시키지 않기 때문에 버퍼를 비워줄 필요가 없다. 

https://starrykss.tistory.com/1971

 

[C++] 입력 함수 : cin(), getline() (and cin.ignore())

입력 함수 : cin(), getline() (and cin.ignore()) 들어가며 C++의 입력 함수인 cin()과 getline() 함수에 대해 알아보자. 그리고 입력 버퍼를 비우는데 사용되는 cin.ignore() 함수에 대해 간단히 알아보자. cin() 헤

starrykss.tistory.com

https://www.acmicpc.net/board/view/47455

 

글 읽기 - cin.ignore()를 사용하면 오답이 되는 이유?

댓글을 작성하려면 로그인해야 합니다.

www.acmicpc.net

 

2. std::cin.clear()

#include <iostream>
using namespace std;

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

char getOperator() {
	while (true) {
		cout << "enter an operator (+,-) : ";
		char op;
		cin >> op;

		std::cin.ignore(32767, '\n');
		if (op == '+' || op == '-') {
			return op;
		}
		else {
			cout << "Invalid operator" << endl;
		}
	}
}

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;
}