在C++中用cin读取同一行中的多个整数

Juv*_*ino 3 c++ input cin

我在从用户读取整数时遇到问题。我可以用

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

但是不知道用户会引入多少整数。我试过这个:

    int n;
    cin >> n; //Number of numbers
    int arrayNumbers[n];

    for(int i=0;i<n;i++){
    cin>>arrayNumbers[i]
    }
Run Code Online (Sandbox Code Playgroud)

用户的输入将类似于: 1 2 3 我的意思是,在同一行中。使用我之前的代码,它只得到第一个数字,而不是其余的。

我怎么能做到?

Hik*_*hat 6

首先使用 std::getline() 将整行读入字符串。然后从输入字符串创建一个字符串流。最后使用 istream_iterator 迭代单个令牌。请注意,此方法将在第一个不是整数的输入处失败。例如,如果使用输入:“ 1 2 ab 3”,那么您的向量将包含 {1,2}。

int main() {
        std::string str;
        //read whole line into str
        std::getline(std::cin, str);
        std::stringstream ss(str);
        //create a istream_iterator from the stringstream
        // Note the <int> because you want to read them
        //as integers. If you want them as strings use <std::string>
        auto start = std::istream_iterator<int>{ ss };
        //create an empty istream_iterator to denote the end
        auto end= std::istream_iterator<int>{};
        //create a vector from the range: start->end
        std::vector<int> input(start, end);
    
    }
Run Code Online (Sandbox Code Playgroud)