2012-02-01 17 views
0

こんにちは皆構造化データのプログラミング割り当てをしています。構造体の仕組みを理解していると思います。getlineをスキップするgetline

私は学生名、ID番号(A-Numbers)、およびその残高のリストを読み込もうとしています。

私は自分のコードをコンパイルすると、最初はすべてが読み込まれますが、2回目はループの周りと毎回ユーザ名の入力を求められますが、getlineをスキップしてA- 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;'を使うことはできません。それは – Neox

+2

@ Neoxさんの作品です - 学生の名前に「John Hancock」のようなスペースがある場合はそうではありません。 –

答えて

3

あなたは動作しません。何をやっている理由は、「>>」演算子は 初めて通じ末尾'\n'を抽出していないということです、次getline がそれを見て、すぐに空の行を返します。

単純な答えは:getline>>を混ぜてはいけません。入力が 行の場合は、getlineを使用します。 行のデータを解析する必要がある場合は、getlineの文字列を使用して std::istringstreamを初期化し、>>を使用してください。

+0

私は間違ったことを理解していますが、あなたの答えの残りの部分は、あなたが私に言おうとしていることについて私を完全に混乱させてしまいました。 – sircrisp

+1

私はcin.ignore()を使用しました。私の問題を解決するgetlineの前に。 – sircrisp

+1

@sircrisp:読み込んだ行を含む 'std :: string'から' std :: istringstream'を作成します。 'std :: cin'と同じように、スペースから区切られた項目をストリームからexctractすることができます:' istr >> item; ' – Xeo

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'); 
} 
関連する問題