2012-02-01 34 views
0

大家好我正在做結構化數據的編程任務,我相信我理解結構如何工作。for loop skipping getline

我正在嘗試閱讀學生姓名,身份證號碼(A號碼)及其餘額的列表。

當我編譯我的代碼時,它會在第一次讀取所有內容,但是第二次在循環中,每次都會提示輸入用戶名,但會跳過getline並直接轉到A-Number A號碼條目。

任何幫助,將不勝感激。試圖找出如何讓循環周而復始的getline工作。

#include <iostream> 
#include <string> 
#include <iomanip> 
using namespace std; 


int main(){ 
    const int maxStudents = 30; 
    struct Students{ 
     string studentName; 
     int aNumber; 
     double outstandingBalance;}; 

    Students students[maxStudents]; 

    for(int count = 0; count < maxStudents-1; count++) 
    { 
     cout<<"Student Name:"; 
       cin.ignore(); 
     getline(cin,students[count].studentName); 
     cout<<"\nA-Number:"; 
     cin>>students[count].aNumber; 
     if(students[count].aNumber == -999) 
      break; 
     cout<<"\nOutstanding Balance:"; 
     cin>>students[count].outstandingBalance; 
    } 

    cout<<setw(20)<<"A-Number"<<"Name"<<"Balance"; 

    for(int count2 = 29; count2 >= maxStudents-1; count2--) 
     cout<<setw(20)<<students[count2].aNumber<<students[count2].studentName<<students[count2].outstandingBalance; 


    system("pause"); 
    return 0; 
} 
+0

你不能只用'cin >> students [count] .studentName;'。它有效btw – Neox 2012-02-01 15:48:16

+2

@Neox - 如果學生的名字中有空格,就像'約翰漢考克'一樣。 – 2012-02-01 15:51:35

回答

3

你在做什麼,不工作的原因是,「>>」運營商 第一次通過不提取後'\n',未來getline 看到它,立即用空行返回。

簡單的答案是:不要混合getline>>。如果輸入是面向行的 ,則使用getline。如果您需要使用>>解析行 中的數據,請使用由getline讀取的字符串初始化 std::istringstream,並使用>>

+0

我明白我做錯了什麼,但你的答案的其餘部分讓我完全不知道你試圖告訴我做什麼。 – sircrisp 2012-02-01 16:24:55

+1

我用了一個cin.ignore();在getline解決我的問題之前。 – sircrisp 2012-02-01 16:37:16

+1

@sircrisp:從包含讀取行的std :: string創建一個'std :: istringstream'。您可以從流你'的std :: cin'做同樣的方式再exctract空間分隔的項目:'ISTR >>項目;' – Xeo 2012-02-01 16:41:52

3

查找C++ FAQ on iostreams

項目15.6您的問題專門處理(「爲什麼我的程序忽略了第一次迭代後,我的輸入請求?」),但你會發現整個頁面是有用的。

HTH,

1

cin.ignore();

在循環的結束。

0

問題出在混合cingetline。格式化的輸入(使用>>運算符)和無格式的輸入(getline就是一個例子)不能很好地協同工作。你一定要讀更多關於它。 Click here for more explanation

這是您的問題的解決方案。 cin.ignore(1024, '\n');是關鍵。

for(int count = 0; count < maxStudents-1; count++) 
{ 
    ... 
    cout<<"\nOutstanding Balance:"; 
    cin>>students[count].outstandingBalance; 
    cin.ignore(1024, '\n'); 
}