问题:想要输入段话,然后将其输出该如何做?
错误方法:
#include <iostream>
#include <string>
using namespace std;
int main(){
string shuru;
cout << shuru <<endl;
}
输入 I am a boy, 发现只会输入第一个字符串,如 “I”。
原因:
cin 遇空格停止识别,虽然输入很长一串字符,但是cin在第一个遇到第一个空格就停止输入,所以,cin只把 I 写入shuru。
正确做法:
#include <iostream>
#include <string>
using namespace std;
int main(){
string shuru;
getline(cin, shuru, '\n');
cout << shuru <<endl;
}
cin 遇空格或换行,会停止识别,如果输入的字符串中带1个或多个空格,则采用getline把停止识别的符号设置为‘\n’(即换行符),就能正确输入输出了。