问题
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?
回答1:
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.
回答2:
Each time you use cin to get something like in cin >> t
, it will leave a newline in the input buffer. so in next operation it will be affected by that and will seem to skip the "wait for return key" and hence abnormality. To avoid that usecin::ignore
.
the documentation says:
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.
The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.
I have written your code in very understandable way but working Let me know if you have any issue
#include <iostream>
using namespace std;
int main() {
int t=0;
cout<<"Enter t\n";
cin>>t;
cin.ignore();
while(t>0)
{ string s,p;
cout<<"Enter s\n";
getline(cin,s);
cout<<"Enter p\n";
getline(cin,p);
cout<<" Values s:"<<s<<" p:"<<p<<"\n";
t--;
}
return 0;
}
回答3:
The newline from cin >> t;
after pressing enter is still in std::cin when getline(cin,s)
is called, resulting in s being empty. The string you enter is actually being stored in p. Try using a different capture method or flushing the cin buffer before using it again.
回答4:
I think it's because getline() doesn't ignore the new line ccharacter, but it reads it in the next call yo getline. Try yo put a getline() before each calle, something like this:
Int main() {
int t;
cin>>t;
string s,p;
getline(cin,s);
while(t--)
{
getline(cin,s);
getline(cin, p);
getline(cin,p);
cout<<s;
}
Hope it helps :)
来源:https://stackoverflow.com/questions/26466329/error-in-getline-input-in-c