0

When I input [1,0,0,1,0] I get output with 1 0 0 1 0 0, I don't know why there is an extra zero and why the while loop doesn't terminate after ].

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
    std::string str;
    std::istringstream is;
    std::vector<int> numbers;
    std::getline(std::cin, str);
    is.str(str);
    char ch;
    is >> ch;
    while (!is.eof())
    {
        int num;
        is >> num >> ch;
        numbers.push_back(num);
    }
    for (auto num : numbers)
        std::cout << num << " ";
    std::cout << std::endl;
    return 0;
}

1 Answers1

2

Change the while loop part will get expected behavior:

  int num;                                                                                                                                                                                                           
  while (is >> num >> ch) {                                                                                                                                                                                            
    numbers.push_back(num);
  } 

The eof check is misused here, so the last character read failed and get a default number 0. Read this answer for more details:

https://stackoverflow.com/a/4533102/1292791

prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42