如何读取带有空格的序列并在用户按C++中的"输入"时停止?

How to read sequences with spaces and stop when the user presses "enter" in C++?

本文关键字:中的 C++ 用户 输入 读取 何读取 空格      更新时间:2023-10-16

作为标题,我是学习C 的初学者。

我想读取包含由空格分离到数组的整数的几个序列(S1,S2,S3 ...(,然后通过按" Enter"来读取S1以读取S2。

这是测试数据:

4 9 6 6

1 2 3 4

3 3 5 6 9 15 18 15 18 30 3 3 5 6 9 15 18 15 18 30 1 9 9 9 25 36

我期望的结果是:

arr [0] = {4,9,6,6}

arr [1] = {1,2,3,4}

arr [2] = {3,3,5,6,9,9,15,18,15,18,30,3,3,3,3,5,6,9,15,15,15,15,18,30,11,9,9,25,36}

我使用了一种耗时的方式将数据读取到我的数组中:

    while(1){
    int i=0,j=0;
    int arr[100][25];
    char test;
    while(1){
    stringstream ss;
    cin.get(test);
    if(test==' '){
        ss<<seq;
        seq.clear();
        ss>>arr[i][j];
        j++;
        continue;
    }
    else if(test=='n'){
        ss<<seq;
        seq.clear();
        ss>>arr[i][j];
        i++;
        j=0;
        break;
    }
    else{
        seq=seq+test;
        }
      }
    }

在线法官将在程序读取大整数时显示" TLE"。

我知道将整数分解为角色是一项耗时的工作,

我该如何处理我的程序?

做到这一点的一种方法可能是使用字符串。下面的示例基于此答案,在字符串中读取每一行,然后按空格将其划分。仅当数字被单个空间拆分时,它才能起作用。拆分数字存储在示例中的字符串向量中,可以使用stoi转换为int

string nums;
while(getline(cin,nums)) {
    istringstream iss(nums);
    vector<string> tokens;
    copy(istream_iterator<string>(iss),
         istream_iterator<string>(),
         back_inserter(tokens));
    // print what is added
    for(int i = 0; i < tokens.size(); i++) {
        cout << tokens[i] << " ";
    }
    cout << endl;
}