C ++中的getline输入中的错误 [英] error in getline input in c++
问题描述
伙计们,我在从getline接收输入时遇到未知错误.我的目的是从用户那里输入一个数字和两个字符串作为输入并打印第一个字符串.这是问题代码
Hi guys i am facing an unknown error while taking input from getline.My purpose is to take a number and two strings as input from the user and print the first string.Here is the problem code
#include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{ string s,p;
getline(cin,s);
getline(cin,p);
cout<<s;
}
return 0;
}
现在,当我输入如下信息时:
Now when i give input like:
1
abababa abb
b
它什么也没打印.为什么会发生?
it doesn’t print anything.Why is it happening?
推荐答案
在cin>>t
之后,流中还剩下一个换行符,因此该换行符将分配给s
,因此cout<<s
似乎什么也没打印(实际上,它会打印换行符.)
在第一个getline
之前添加cin.ignore(100, '\n');
以输入换行符.
After cin>>t
, there is a newline remaining in the stream, then the newline will be assigned to s
, so cout<<s
seems to print nothing(Actually, it prints a newline).
add cin.ignore(100, '\n');
before first getline
to ingore the newline.
这篇关于C ++中的getline输入中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!