Unable to Accept String Inputs in main() function after ending a seperate loop

I using only the main function I am trying to input strings into different variables while in a loop. Problem is after I 'Ctrl+z' the program returns 0 and closes

This works:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 int main()
{
    //vecotr<string>disliked={ "Pig", "Cow"}
    vector<string>words;
    for(string disliked; cin>>disliked;)
        words.push_back(disliked);

cout<< words.size()<<endl;


    for(int i=0; i<words.size();++i)
        { if(words[i]=="Apple")
        cout<<"***\n";

        else
            cout<<words[i]<<endl;
        }
}


This gives me trouble after exiting with Ctrl+Z
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

int main()
{
   
    vector<string>words;
    for(string disliked; cin>>disliked;)
        words.push_back(disliked);

cout<< words.size()<<endl;//everything after this doesn't work

for (string inputz;cin>>inputz;)//added this line to allow user inputz
    for(int i=0; i<words.size();++i)
        { if(words[i]==inputz)//changed apple to inputz
        cout<<"***\n";

        else
            cout<<words[i]<<endl;
        };
}
Last edited on
How did you exit the first loop?

What is the state of the stream when you get to the next loop?

Did you run the program with your debugger to try to see what is happening?

I exit the first loop with ctrl+z
Ctrl-z is the way to indicate "end-of-file" from the terminal in Windows. Once you've indicated that cin has reached the eof, then you can't read any more from it until you reset the stream state with cin.clear(). Put it after the first loop.
cin.clear(); works. I also used it for another code. Thanks!

I don't understand why it wasn't in the book.
Last edited on
Topic archived. No new replies allowed.