繁体   English   中英

为什么 cin.ignore() 忽略我的 getline 输入的第一个字符?

[英]Why is cin.ignore() ignoring the first character of my getline input?

So according to Eclipse, the getline function stores the entire text line from stream along with the newline and "terminating null character." 我完全不知道那是什么意思。

我想要得到的 output 正在使用 function 打印两个并行的 arrays。 这个 function 是一个 void function 包含 3 个参数,第一个数组,第二个数组和常量 integer 数组大小值。

我能够毫无问题地将输入存储到第一个数组中。

    const int SIZE = 5;
    double firstArray[SIZE];

    // range-based `for` loop to get user input
    for (double& floatNum : firstArray)
    {
        cout << "Enter a floating point number: ";
        cin >> floatNum;
    } 

但是,第二个数组是字符串类型,事情变得很奇怪。

    string secondArray[SIZE];

    // `for` loop to get user input
    for (int i = 0; i < SIZE; i++)
    {
        cout << "Enter a name: ";
        cin.ignore();
        getline(cin, secondArray[i]);
    }

My desired output is to print out both arrays using a function call in main() , printParallel(array1, array2, sizeofarray) , simultaneously using a while loop inside a function, which I've attempted here:

void printParallel(double arrayOne[], string arrayTwo[], const int NUM)
{
    int i = 0;
    while (i < NUM)
    {
        cout << arrayOne[i] << " " << arrayTwo[i] << endl;
        i++;
    }

}

但 output 稍有偏差:

Enter a floating point number: 1.23
Enter a floating point number: 1.23
Enter a floating point number: 1.23
Enter a floating point number: 1.23
Enter a floating point number: 1.23
Enter a name: AA AA
Enter a name: AA AA
Enter a name: AA AA
Enter a name: AA AA
Enter a name: AA AA
1.23 AA AA
1.23 A AA
1.23 A AA
1.23 A AA
1.23 A AA

有人可以解释这里发生了什么吗? 第一个“A”似乎被 null 字符覆盖。 另外,为了将来更好地解决问题,有没有更好的方法让我提问?

问题:

cin.ignore(); 循环内

这相当于cin.ignore(1);

它忽略了字符串输入的每个第一个字符。 这就是为什么所有那些“AA AA”都变成“A AA” (第一个“A”被cin.ignore()忽略)。

除了第一个“AA AA” 在这种情况下, cin.ignore()实际上在输入前一个循环的最后一个浮点数后忽略了\n 因此,幸运的是,第一个字符串 output 是正确的。

解决方案:

在进入该循环之前只调用一次cin.ignore() ,而不是为每个字符串输入调用它。

getline(cin, secondArray[i]); 在这些输入的末尾吃掉\n ,你不需要cin.ignore()它们。

// `for` loop to get user input
cin.ignore(); // solution
for (int i = 0; i < SIZE; i++)
{
    cout << "Enter a name: ";
    // cin.ignore(); <-- Mistake
    getline(cin, secondArray[i]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM