Reputation: 127
I have a c++ code like this:
#include<iostream>
using namespace std;
int main()
{
char str[20];
while(true)
{
cin>>str;
cout<<"Your input is "<<str<<endl;
}
}
and when I use linux shell script like :
echo t|./test
it shows result I don't want to see: enter image description here
it just come out infinite "Your input is t"
I guess it's because the thing in "cin" doesn't disappear. I add these two lines but it doesn't work:
cin.clear();
cin.ignore(1024,'\n');
What I want is that it outputs one sentence, and waits for my next input. Just like I do "./test"
Upvotes: -1
Views: 58
Reputation: 409442
What happens is that in the first iteration of the loop the input is read as usual.
Then in the second iteration the pipe has closed, and the input operation will start to fail. But that doesn't mean the value of str
will be changed. Instead it's the opposite: The value of str
stays the same.
So you have an infinite loop where input fails but the value stays the same.
And it doesn't matter if you clear the status flags of std::cin
, the pipe it still closed and can not provide any other input.
If you still want an infinite lop, but only read the one input put the input into a condition to know if it failed or succeeded:
if (std::cin >> str)
{
// Managed to read some input
std::cout << "Your input is " << str << '\n';
}
Upvotes: 3