Reputation: 5
Just wrote 3-4 lines to reproduce the problem. After using cin >>
inside a "for loop" to repeatedly take input, all the next cin >> (s)
always get skipped.
Anything/Everything other than cin
works fine.(just want to know why this happens and what shall I do to be able to use cin
further in the program)
for(int x;cin >> x;){
cout << x <<endl;
}
int a;
cin >>a;
No error message.
Upvotes: 0
Views: 540
Reputation: 1246
The second expression in the for
header is the loop condition; the loop will continue running as long as this is true. Your condition is always true, so the loop is never exited.
You could add some code inside your loop to exit it, e.g. if (x == 0) break;
However, I would suggest redesigning the loop. Your loop condition is very unusual, and will give most people a bit of head-scratching before they figure out what's going on. Perhaps you can put the reading operation inside the loop body?
How >>
works
For std::basic_istream
(std::cin
is one of these), the >>
operator is overridden to implement formatted data extraction, and it's designed to be chainable (e.g. cin >> a >> b >> c
). This works because:
>>
is left-associative, so it groups as ((cin >> a) >> b) >> c)
>>
returns a reference to the stream object, so you can keep adding more >>
as much as you like.Also, a std::basic_istream
can be converted to bool
, and will be true
as long as no error has occurred. Thus, your loop condition is always cin
, and since you're presumably not getting errors, is always true.
Upvotes: 0
Reputation: 385174
Whatever you're doing to make cin >> x
fail (to break the loop) will just affect cin >> a
too, as it's the same dang command!
The object cin
doesn't "know" about your loop logic, and neither does your operating system/terminal, neither could it in general know that you intended for some sort of "reset" to happen once the loop was broken. You'd have to signal that yourself. However, it's likely you can't just patch that in because:
std::cin
object will have the EOF flag set on it, and this persists. (Sometimes you can clear this manually but I wouldn't recommend doing so, as you can get into confusion on the sending side, depending on your platform…)You will have to find another way to break your loop, either with some "magic reserved number", by having a more sophisticated input protocol, by only reading some number n of initial inputs, or some other means that depends on what you're trying to do.
Upvotes: 5