如何从命令行中读取以空格分隔的输入数字

How to read input numbers separated with spaces from command line c++

本文关键字:分隔 空格 输入 数字 读取 命令行      更新时间:2023-10-16

我有下面的代码:

    std::cin >> N >> T;
    std::vector<int> width;
    for (int w = 0; w < N; w++)
    {
        int tmp;
        std::cin >> tmp;
        width.push_back(tmp);
    }

如果我把3 2 3 4作为控制台的输入,它被空白分隔并存储为矢量数组。

我的问题是它如何能够读取由空格分隔的cin中的整数值?我以为你应该做4次std::cin >> tmp输入?

你的意思是:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>

int main( int argc, char **argv )
{
   std::vector<int> v;
   v.reserve( std::max( 0, argc - 1 ) );
   for ( int i = 1; i < argc; i++ ) v.push_back( std::atoi( argv[i] ) );
   //...
}