简体   繁体   English

在 C++ 中从 cin 中读取空格分隔的数字

[英]Reading space-separated numbers from cin in C++

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:我试过使用stringstream但由于某种原因它不适用于两行输入:

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?有没有一种从行中提取数字的好方法(不使用 boost 库),我的代码有什么问题?

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.当您在 while 循环中使用 lineOfInput 作为条件时,它将一直运行,直到进入失败状态,因此具有相同字符串流的第二个 while 将永远不会运行,因为它不会返回 true。 Just add lineOfInput.clear() and everything will be all right.只需添加lineOfInput.clear()一切都会好起来的。

Also when you run into a problem like this it's helpful to debug and see what really happens.此外,当您遇到此类问题时,调试并查看实际发生的情况会很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM