读入一行由空格隔开的数字

当给你一行未知个数的数字时,需要读字符来处理,比较麻烦。
可以用C++封装的stringstream来处理的。

#include 
#include 
#include 
using namespace std;
int main()
{
    int a[1005], cnt;
    string s;
    while(getline(cin, s))
    {
        cnt = 0;
        stringstream ss(s);
        int x;
        while(ss >> x)
        {
            a[cnt++] = x;
        }
        for(int i = 0; i < cnt; i++)
        {
            printf("%d ", a[i]);
        }
        puts("");
    }
    return 0;
}

你可能感兴趣的:(C++,C++)