c++不固定数目的数字的输入

时间:2025-03-14 17:21:06

c++不固定数目的数字的输入

写算法题有时候需要不固定个数的数组的输入,有时是一个测试样例,输入一行数字,有时候是多个测试样例,输入多行不固定数目的数字,所以总结一下,具体如下:

一行不固定个数的整数的输入

//方法1:getchar 
//代码通过()从缓存中读取一个字节,这样就扩充了cin只能用空格和TAB两个作为分隔符。
//这很精巧。发现是’\n’就知道一行结束了 
vector<int> nums;
int num;
while(cin>>num){
    nums.push_back(num);
    if(getchar() == '\n')
        break;
}
//方法2:
vector<int> nums;
int num;
while(cin>>num){
    nums.push_back(num);
    if(cin.get() == '\n')
        break;
}

多行不固定数目的数字输入

#include <bits/stdc++.h>
#include <iostream>

using namespace std;
int main()
{

    char c;
    while ((c = getchar()) != '\n')
    {
        vector<int> nums;
        int num;
        ungetc(c, stdin);
        while (cin >> num)
        {
            nums.push_back(num);
            if (getchar() == '\n')
                break;
        }

        for (auto x : nums)
        {
            cout << x << " ";
        }
        cout << endl;
    }
    return 0;
}