-2

I just wanted to split the inputted string to an vector of strings. I have 2 problems:

  1. If I enter nothing into the console , params isn't empty (but it should be)
  2. If I enter a word and add a space at the end , the word gets stored into params twice.

This is my code:

std::string input;
std::string buffer;
std::vector<std::string> params;
std::cout << "Input: " ;
std::getline(std::cin, input);

std::istringstream stream;
stream.str(input);


while(!(stream.eof()))
{
  stream >> buffer;
  params.push_back(buffer);
}

// printing content of params

for (int i = 0; i <params.size(); i++)
{
  std::cout << "Params :" << params[i] << std::endl;
}
std::cout << params.size() << std::endl;

I think the problem could be the while condition.

I would be grateful for any help you could give me.

Marius Bancila
  • 15,287
  • 7
  • 44
  • 84
Rafa
  • 101
  • 1
  • 2

1 Answers1

4

The problem here is your loop extracting strings from the stringstream, doing while (!stream.eof()) does not work as you expect it to. The reason is that the eofbit flag is not set until after you try to read from beyond the end of the stream. That leads you to iterate through the loop one time even through the input was empty, and also you will iterate once more that the number of words in the input adding the last word twice to the vector.

Instead do

while (stream >> buffer)
    params.push_back(buffer);
Some programmer dude
  • 363,249
  • 31
  • 351
  • 550