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

Jun 9, 2018 at 10:57pm
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 Jun 10, 2018 at 12:07am
Jun 9, 2018 at 11:38pm
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?

Jun 10, 2018 at 12:00am
I exit the first loop with ctrl+z
Jun 10, 2018 at 12:20am
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.
Jun 10, 2018 at 5:09am
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 Jun 10, 2018 at 5:19am
Topic archived. No new replies allowed.