簡體   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