push_back not working in loop

In the code below, I tried to let the user input text, and it would output the first word. However, whenever I try the program to input the text, it doesn't output anything.

//code below
#include <iostream>
#include <vector>

using namespace std;

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

cout << words[0];
}
Last edited on
It most likely doesn't reach the cout statement. That's because there is no obvious way to exit from the loop. For example, below, the loop ends when the user types "stop".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string> words;
    
    for(string winput; cin>>winput && winput != "stop"; )
        words.push_back(winput);

    cout << words[0];
}

Topic archived. No new replies allowed.