#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string input = "";
// How to get a string/sentence with spaces
cout << "Please enter a valid sentence (with spaces):\n>";
getline(cin, input);
cout << "You entered: " << input << endl << endl;
// How to get a number.
int myNumber = 0;
while (true) {
cout << "Please enter a valid number: ";
getline(cin, input);
// This code converts from string to number safely.
stringstream myStream(input);
if (myStream >> myNumber)
break;
cout << "Invalid number, please try again" << endl;
}
cout << "You entered: " << myNumber << endl << endl;
// How to get a single char.
char myChar = {0};
while (true) {
cout << "Please enter 1 char: ";
getline(cin, input);
if (input.length() == 1) {
myChar = input[0];
break;
}
cout << "Invalid character, please try again" << endl;
}
cout << "You entered: " << myChar << endl << endl;
cout << "All done. And without using the >> operator" << endl;
return 0;
}
http://www.cplusplus.com/forum/articles/6046/ 에서 가져옴 저자: Zaita
Too many questions keep popping up with the same problem.
How do I get user input from cin using >> into X type.
Using the >> operator opens you up to alot of problems.
Just try entering some invalid data and see how it handles it.
Cin is notorious at causing input issues because it doesn't
remove the newline character from the stream or do type-checking.
So anyone using cin >> var; and following it up with another
cin >> stringtype; or getline(); will receive empty inputs.
It's best practice to NOT MIX the different types of input methods from cin.
I know it's going to be easier to use cin >> integer; than the code below.
However, the code below is type-safe and if you enter something
that isn't an integer it will handle it. The above code will simply
go into an infinite loop and cause undefined behaviour in your application.
Another dis-advantage of using cin >> stringvar;
is that cin will do no checks for length, and it will break on a space.
So you enter something that is more than 1 word, only the first word is
going to be loaded. Leaving the space, and following word still in
the input stream.
A more elegant solution, and much easier to use is the getline(); function.
The example below shows you how to load information, and convert it between
types.
'c·c++ > c++ 프로그래밍' 카테고리의 다른 글
문자열 경우의 수 c++버전 (0) | 2011.12.28 |
---|---|
gcc 로 컴파일하기 (0) | 2011.12.16 |
cin 버퍼에 남은 글자수 세기 (0) | 2011.12.03 |
cin을 이용하여 정수를 안전하게 입력받기. (0) | 2011.12.03 |
c++ 윈도우에서 키보드를 모니터하기 kbhit() (0) | 2011.12.03 |