2016-04-14 7 views
-2

の値を表示:以下を含むtdogicatzhpiguと別のファイル:別の行にC++は、文字列配列に.txtファイルから文字列を追加し、私は、次を含むファイル有する配列

dog 
pig 
cat 
rat 
fox 
cow 

を。

次のコードは、do whileループであるメニュー内でこれを行う試みを示しています。私は選択の1以内のアレイを印刷する場合

if (selection == 1) { 

     //Gets the characters from the textfile and creates an array of characters. 
     fstream fin1("text1.txt", fstream::in); 
     if (fin1.is_open()) 
     { 
      cout << "text1.txt successfully added to an array" << endl; 
      while (!fin1.eof()) { 
       if (!fin1.eof()) { 
        for (int i = 0; i < 14; i++) { 
         for (int e = 0; e < 14; e++) { 
          fin1 >> chArray[i][e]; 

         } 
        } 
       } 
      } 
     } 
     else if (!fin1.is_open()) 
     { 
      cout << "ERROR: "; 
      cout << "Can't open text1.txt file\n"; 
     } 
     fin1.close(); 
     //Get the string values from the file and add into an array of strings 

     fstream fin2("search1.txt", fstream::in); 
     if (fin2.is_open()) { 
      cout << "Search1.txt successfully added to an array" << endl; 
      cout << "------------------------------------------------------------------------" << endl; 
      while (!fin2.eof()) { 
       if (!fin2.eof()) { 
        for (int j = 0; j <= 6; ++j) { 
         getline(fin2, wordsArray[j]); 

        } 
       } 
      } 
     } 

は今、それはしかし、私は再びchArrayの内容を表示しようとしています次の選択2で、すべてが順調である、両方のために正しく表示されるが、それはアウト"t"ミス何らかの理由 のために:

else if (selection == 2) { 
     for (int i = 0; i < 14; i++) { 
      cout << chArray[0][i] << endl; 
     } 

選択3で、wordsArrayを表示しようと、何もまったく表示しない、ここで選択3のためのコードは次のとおりです。

else if (selection == 3) { 
     for (int j = 0; j <= 6; ++j) { 
      cout << wordsArray[j] << endl; 
     } 
+0

問題を複製できませんでした。指定した入力で実行すると問題なく動作します。なぜ文字を格納するために二次元配列を使用していますか? –

+0

あなたのプログラムではどこに配列を宣言していますか? –

+0

配列はdo whileループの外で宣言されていますが、配列内の各要素に各文字を格納する方が好きですが、正しく動作させる方法がわかりません。ファイル内では、文字間に空白を入れない – jbob

答えて

2

(私はあなたが作る必要がある変更を書かれているので、それがあるように、他のコードを維持)、これを試してみてください。このことができます

string chArray; 
string wordsArray[6]; 

do 
{ 
....//other code 

if (selection == 1) 
{ 

    if (fin1.is_open()) 
    { 
     cout << "text1.txt successfully added to an array" << endl; 
     if(!getline(fin1,chArray))//read the whole line from the file into the string 
     //show error message that a file was not read successfully 
    } 

    ..... 

    for (int j = 0; j < 6; ++j)//change j<=6 to j<6 since your array has 6 elements 

    ..... 

} 
else if (selection == 2) 
{ 
    for (int i = 0; i < 14; i++) 
     cout << chArray[i] << endl;//no need to access this as two dimensional array 

..... 

} 
else if (selection == 3) 
{ 
    for (int j = 0; j < 6; ++j)//change j<=6 to j<6 since your array has 6 elements 
     .... 
} 

}while(selection != your exit value); 

希望を。

+0

私は助けていただきありがとうございます、私は変更を実装し、それがどのように行くのか教えてください – jbob

関連する問題