现象:在cin后使用getline时,getline无法读取输入的字符串
解决方法:1.不在cin后使用getline
2.在cin后进行一次getline的dummy读操作,代码如下
string dummy;
getline(cin, dummy);
示例:
愚蠢的博主在写小程序时敲了如下代码:
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { int num; cin >> num; cout << "test" << endl; string a = ""; getline(cin, a); cout << a << endl; cout << "test2" << endl; return 0; }运行结果如下:
>>2
<<test
<<
<<test2
<<
Process finished with exit code 0
之后经过一番折腾,最后在google中找到了解决方法,重写后的代码如下:
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { int num; string dummy; cin >> num; getline(cin,dummy); cout << "test" << endl; string a = ""; getline(cin, a); cout << a << endl; cout << "test2" << endl; return 0; }运行后如下:
>>2
<<test
>>hehe
<<hehe
<<test2
Process finished with exit code 0
参考来源:http://mathbits.com/MathBits/CompSci/APstrings/APgetline.htm