在 cpp 中使用 getline 输入数组中的空格分隔数字

Input Space Separated Numbers in arrays using getline in cpp

本文关键字:空格 分隔 数组 数字 getline cpp 输入      更新时间:2023-10-16

我一直在研究一个问题,在这个问题中,我需要在 CPP 的两个单独数组中获取空格分隔的输入(<=10),然后在下一行中获取其他一组空格分隔的输入。我为此在 cpp 中使用了 getline 函数。我面临的问题是接受输入的最后一行。我不知道我面临什么问题。当最后一行出现时,输出停止并等待我键入内容,然后它提供输出。这是我的代码。

while(test--)
{
    int len[100];
    int pos[100];

    string a,b,code;
        // int t=1;

    cin>>code;

    cin.ignore();//ignores the next cin and waits till a is not input

    getline(cin,a);

  //  deque<char> code1;
   // code1.assign(code.begin(),code.end());


    int k=0;
    int t=a.length();
    for(int i=0;i<t/2+1;i++)//converts two n length arrays pos[] and len[] 
    {
        scanf("%d",&len[i]);
    while(a[k]==' ')
    {
        k++;
    }


            pos[i]=a[k]-48;
            k++;
               }

        //int c;}

'

您的代码令人困惑,看起来应该不起作用。您正在使用带有cin/scanf的阻塞输入,因此如果标准输入上没有准备好输入,它会等待您是正常的。

这是您尝试执行的操作:

  • 使用getline将行读入名为 a 的字符串。
  • 使用 scanf 将数据从a读取到数组中。

但是,scanf不是为此而生的。scanf函数从键盘获取输入。我想你想使用 sscanf 输入字符串a中的值。

但更好的是使用字符串流。

起初我以为你是在尝试从命令行读取输入的长度,所以我建议这样做:

size_t arr_len;
cin >> arr_len;
if (cin.fail())
{
    cerr << "Input error getting length" << endl;
    exit(1);
}
int* len = new int[arr_len];
int* pos = new int[arr_len];
for (int count = 0; count < arr_len; count++)
{
    cin >> len[count];
    if (cin.fail())
    {
        cerr << "Input error on value number " << count << " of len" << endl;
        exit(1);
    }        
}

for (int count = 0; count < arr_len; count++)
{
    cin >> pos[count];
    if (cin.fail())
    {
        cerr << "Input error on value number " << count  << " of pos" << endl;
        exit(1);
    }
}
delete [] pos;
delete [] len;

然后我看得更仔细了。看起来这就是您想要做的。我使用的是std::vector而不是int[],但如果你真的想要,改变它并不难。

string line;
getline(cin, line);
if (cin.fail())
{
    cout << "Failure reading first line" << endl;
    exit(1);
}
istringstream iss;
iss.str(line);
vector<int> len;
size_t elements = 0;
while (!iss.eof())
{
    int num;
    iss >> num;
    elements++;
    if (iss.fail())
    {
        cerr << "Error reading element number " << elements << " in len array" << endl;
    }
    len.push_back(num);
}
getline(cin, line);
if (cin.fail())
{
    cout << "Failure reading second line" << endl;
    exit(1);
}
iss.clear();
iss.str(line);
vector<int> pos;
elements = 0;
while (!iss.eof())
{
    int num;
    iss >> num;
    elements++;
    if (iss.fail())
    {
        cerr << "Error reading element number " << elements << " in pos array" << endl;
    }
    pos.push_back(num);
}