Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何接受空格分隔的整数并将它们存储在C++;?_C++ - Fatal编程技术网

C++ 如何接受空格分隔的整数并将它们存储在C++;?

C++ 如何接受空格分隔的整数并将它们存储在C++;?,c++,C++,我尝试接受N个间隔的整数,将它们存储在一个向量中并打印出来。这是我的代码: #include <string> #include <vector> using namespace std; int main() { string rawInput; vector<string> numbers; while( getline( cin, rawInput, ' ' ) ) { numbers.push_back(rawInput);

我尝试接受N个间隔的整数,将它们存储在一个向量中并打印出来。这是我的代码:

#include <string>
#include <vector>

using namespace std;
int main() {
  string rawInput;
  vector<string> numbers;
  while( getline( cin, rawInput, ' ' ) )
  {
    numbers.push_back(rawInput);
  }
  for (int j = 0; j < sizeof(numbers)/sizeof(numbers[0]); ++j) {
    cout << numbers[j] << " ";
  }
}
#包括
#包括
使用名称空间std;
int main(){
字符串输入;
向量数;
while(getline(cin,rawInput,'))
{
数字。推回(输入);
}
对于(int j=0;jcout对于空格分隔的整数,不要使用
getline
。在构造整数时,换行符算作空格

试着这样做:

std::vector<int> database;
int number;
while (cin >> number)
{
    database.push_back(number);
}

嗯,逐行读取会增加不必要的复杂性。

当您使用调试器运行此程序时,它会错误地执行的第一件事是什么?
sizeof(numbers)/sizeof(numbers[0])
没有任何意义。
数字
是一个向量,而不是数组。使用其成员函数检查它包含多少元素。在@Mat所说的内容的基础上,使用
数字。大小()
instead@ScottHunter没有输出。我尝试接受N个间隔的整数,将它们存储在一个向量中并打印它们——使用
std::istringstream
使这非常容易。
std::vector<int> database;
std::string text_line;
while (getline(cin, text_line))
{
    int number;
    std::istringstream line_stream(text_line);
    while (line_stream >> number)
    {
        database.push_back(number);
    }
}