problem with cin>> and getline

Jul 2, 2013 at 1:50pm
I have problem with cin>> and getline. The getline function somehow steal the input I enter earlier from the cin>> function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
#include<iostream>
#include<string>
using namespace std;
{
	string line;
	int tc,count=1;
	cin>>tc;
	while(tc--)
	{
			getline(cin,line);
			translate(line,count);
			count++;
	}
}
Jul 2, 2013 at 1:57pm
You are half-way to an explanation. The getline() doesn't 'steal' anything which was accepted by an earlier cin >>. What it does is use anything which was left over, in the input buffer after that cin, which will usually be a newline character '\n', but if the user typed something other than was requested by the earlier input, there could be many characters remaining.

After cin >> use cin.ignore() or something like cin.ignore(1000, '\n') to get rid of the unwanted characters in the buffer.
Last edited on Jul 2, 2013 at 1:58pm
Jul 2, 2013 at 1:57pm
closed account (Dy7SLyTq)
after the cin>>tc write cin.flush();
Jul 2, 2013 at 2:17pm
It works! Thanks!
Jul 2, 2013 at 4:05pm
sorry 2 questions, cin.flush() the same as cin.sync()?

and how does while(int--) work? I though while required a bool or comparable statements?

Edit: Just continues till it hits 0, sorry ignore the second question that was dumb.

Last edited on Jul 2, 2013 at 4:08pm
Jul 2, 2013 at 5:31pm
std::istream doesn't have a member flush as described by the standard.
Last edited on Jul 2, 2013 at 5:31pm
Jul 8, 2013 at 5:21pm
int main()
#include<iostream>
#include<string>
using namespace std;


#include<iostream>
#include<string>
using namespace std;

These should be written at the very start of your program for your compiler, not inside your main function
Jul 8, 2013 at 5:26pm
closed account (Dy7SLyTq)
doesnt make a difference in this case though (well if its inside the brackets; it cant be immediatly after main like that i believe but int main() { headers and std } is fine)
Topic archived. No new replies allowed.