Home > OS >  Reading space-separated numbers from cin in C
Reading space-separated numbers from cin in C

Time:06-13

I have to put the numbers from each line of input into different vectors without knowing how many numbers there will be in one line of input. For example:

1 2 3
4 5 6 -7

should result in

a = {1, 2, 3};
b = {4, 5, 6, -7};

Note that the number of integers in each line is unknown.

I've tried using stringstream but for some reason it didn't work for two lines of input:

int main() {
  vector<int> a, b;

  string c;
  int number;
  stringstream lineOfInput;

  getline(cin, c);
  lineOfInput.str(c);
  c = "";

  while (lineOfInput >> number) {
    a.push_back(number);
  }

  getline(cin, c);
  lineOfInput.str(c);
  c = "";

  while (lineOfInput >> number) {
    b.push_back(number);
  }

  return 0;
}

The first vector is filled normally, but the second doesn't. Is there a good way to extract numbers from lines (without using boost library) and what's the problem with my code?

CodePudding user response:

When you use lineOfInput as a condition in a while loop it will run until it enters the fail state, so the second while with the same stringstream will never run because it doesn't return true. Just add lineOfInput.clear() and everything will be all right.

Also when you run into a problem like this it's helpful to debug and see what really happens.

  • Related