一行输入多个数字

gel*_*ne1 4 c++ input

我想知道如何在一条线路上接受多个数字而不事先知道多少.

所以,例如,如果我有1 2 3 4输入,我可以使用:

cin >> a >> b >> c >> d;
Run Code Online (Sandbox Code Playgroud)

但如果我不知道数量是4那么我就不能使用这种方法.将输入存储到向量中的正确方法是什么?

提前致谢

Vla*_*cow 7

您可以读取所有输入,直到std :: string类型的对象中的新行字符,然后从该字符串中提取数字并将它们放置在矢量中.

这是一个随时可用的例子

#include <iostream>
#include <sstream>
#include <iterator>
#include <string>
#include <vector>

int main() 
{
    std::string s;

    std::getline( std::cin, s );

    std::istringstream is( s );

    std::vector<int> v( ( std::istream_iterator<int>( is ) ), std::istream_iterator<int>() );

    for ( int x : v) std::cout << x << ' ';
    std::cout << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果你输入一行数字

1 2 3 4 5 6 7 8 9 
Run Code Online (Sandbox Code Playgroud)

然后从向量输出的程序将是

1 2 3 4 5 6 7 8 9 
Run Code Online (Sandbox Code Playgroud)

在这个程序中,您可以替换语句

std::vector<int> v( ( std::istream_iterator<int>( is ) ), std::istream_iterator<int>() );
Run Code Online (Sandbox Code Playgroud)

对于

std::vector<int> v;
int x;

while ( is >> x ) v.push_back( x );
Run Code Online (Sandbox Code Playgroud)