-2
std::vector<std::string> words;
std::string word;
while (std::cin >> word)
words.push_back(word);
cout<<words[1];

i am using this to take input to create an array of words with whitespaces.but after ending of sentence using Enter, i am not getting any output.

ashlin
  • 9
  • 2

2 Answers2

2

i am using this to take input to create an array of words with whitespaces.but after ending of sentence using Enter, i am not getting any output.

That's because

while (std::cin >> word)
  words.push_back(word);

does not stop when you press Enter

It stops when there is no more data in std::cin. You have to enter EOF to get out of the while loop.

Useful link: How do i enter an EOF character in this program?.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

using

getline(cin,word) 

instead of

cin<<word 

will allow you to input words with whitespaces.

Even, vector starts at index 0, hence output

words[0]

instead of

words[1]

will output the entered value. that is the problem.

Ramakanth Putta
  • 676
  • 4
  • 15