问题描述
我想知道如何在一行中接受多个数字,而不必事先确切知道有多少个数字.
I want to know how I can accept multiple numbers on one line without exactly knowing in advance how many.
例如,如果我输入1 2 3 4
,则可以使用:
So for example if I have 1 2 3 4
as input I could use :
cin >> a >> b >> c >> d;
但是,如果我不知道数量是4,那么我将无法使用该方法.将输入存储到向量中的正确方法是什么?
But if I don't know that the amount is 4 then I can't use that approach. What would be the right way to store the input into a vector?
预先感谢
推荐答案
您可以读取所有输入,直到在std :: string类型的对象中换行符为止,然后从该字符串中提取数字并将其放置在例如向量.
You can read all input until the new line character in an object of type std::string and then extract numbers from this string and place them for example in a vector.
这是一个随时可以使用的示例
Here is a ready to use example
#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;
}
如果您要输入一行数字
1 2 3 4 5 6 7 8 9
那么矢量的程序输出将是
then the program output from the vector will be
1 2 3 4 5 6 7 8 9
在此程序中,您可以替换语句
In this program you could substitute statement
std::vector<int> v( ( std::istream_iterator<int>( is ) ), std::istream_iterator<int>() );
为
std::vector<int> v;
int x;
while ( is >> x ) v.push_back( x );
这篇关于一行输入多个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!