2016-05-04 17 views
0

getlineを使用して情報を格納すると、テキストファイルに列全体を格納する配列があり、区切り文字として'/'を使用しますが、私はプログラムを実行するとa[i]などで、その次line.`上に移動させる第1ラインと店舗がgetline inループを使用して配列に格納する

const int MAX = 20; 
int main(){ 

    string menuname; 
    string a[MAX]; 
    string d[MAX]; 
    string b[MAX]; 
    string c[MAX]; 
    string line; 
    bool error = false; 
    ifstream openFile; 
    int counter = 0; 

    do{ 
     cout << "Please enter the name of the menu you would like to open: "; 
     cin >> menuname; 
     menuname += ".txt"; 
     openFile.open(menuname.c_str()); 
     if(openFile.fail()){ 
      cerr << "Unable to open file, please re-enter the name.\n"; 
      error = true; 
     } 
    //Determine how many lines long the text file is 
     while(getline(openFile, line)){ 
      ++counter; 
     } 
     //Testing the counter 
    cout << counter; 
    }while(error == true); 

    while(! openFile.eof()){ 
     for(int i = 0; i < counter; i++){ 
      getline(openFile, a[i], '/'); 
      getline(openFile, b[i], '/'); 
      getline(openFile, c[i], '/'); 
      getline(openFile, d[i]); 
     } 
    } 
    for(int i = 0; i < counter; i++){ 
     cout << a[i] << b[i]; 
    } 
} 

現在、エラーはありません、と私はちょうどである出力を示すことにより、カウンタ変数をテストしています正しく動作しますが、プログラムの最下部では、私が格納している配列のうち2行を出力する小さなテストを作成しましたが、何も出力せず、カウンタの値を表示して終了します。

+0

** [MCVE] **を入力してください。あなたの質問にエラーメッセージ(コンパイル時間またはランタイム)を含めてください。リンカのエラーについては、リンカのコマンドラインを提供してください(そうでない場合は、未定義の参照/未解決の外部シンボルエラーとは何ですか、どうすれば修正できますか?)(http://stackoverflow.com/questions/ 12573816 /未定義 - 参照 - 未解決 - 外部記号 - エラー - および - 私 - 修正)第1)。また、デバッガでコードを実行し、すべての単一行をステップ実行する際に、実行時エラーについてのご意見をお寄せください。 –

+0

アレイ全体に行を保存したいですか?または1文字ですか? Bcozはgetl​​ineを使って読み込み、値を格納するために1文字を渡しています。 –

+0

テキストファイルはxxx/xxx/xxx/xxxの形式で、複数の行があり、配列全体に列全体を格納したい – Thecube

答えて

3

問題は、実際にデータを保存するときにファイルの最後にあることです。

while(getline(openFile, line)){ 
    ++counter; 
} 

最後までファイルを読み取り、文字列にEOFフラグを設定します。そして、あなたは

while(! openFile.eof()){ 
    for(int i = 0; i < counter; i++){ 
     getline(openFile, a[i], '/'); 
     getline(openFile, b[i], '/'); 
     getline(openFile, c[i], '/'); 
     getline(openFile, d[i]); 
    } 
} 

に取得し、EOFフラグが設定されているので、whileループが実行されることはありません。あなたが本当にのためのカウンタを必要とするすべては終わりの表示ループであるので、我々は

while(getline(openFile, a[counter], '/') && getline(openFile, b[counter], '/') && 
     getline(openFile, c[counter], '/') && getline(openFile, d[counter])){ 
    counter++; 
} 

のように1つのループにカウンタループと読書ループを組み合わせることができますそして今、我々は完全なファイルを読み込むとのカウントを取得します読み取られた行数。

+0

私は元のカウンタループと 'while(!openfile.eof()){'を使ってforループを削除しようとしましたが、提案した新しいwhileループを使用していますが、画面に何も出力しません。 – Thecube

+0

@Thecubeあなたのコードはどうなっていますか?[this](http://coliru.stacked-crooked.com/a/3465d79242b88dff) – NathanOliver

+0

getline(openFile、a [i]、 '/')&& getline(openFile、b [i]、 '/')&& getline(openFile、c [i]、 '/' )&& getline(openFile、d [i])){ カウンタ++; } 'は私が宣言されていない問題があります。これは先にforループを使用した場所です。 – Thecube

関連する問題