2016-04-14 107 views
-2

I的值具有包含以下內容的文件:tdogicatzhpigu和含有下列另一個文件:在不同的行C++從.txt文件添加字符串轉換成字符串數組,並顯示該陣列

dog 
pig 
cat 
rat 
fox 
cow 

以下代碼顯示了我在一個do while while循環的菜單中執行此操作的嘗試。

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]); 

        } 
       } 
      } 
     } 

現在如果我打印選擇1中的陣列,它會顯示正確兩種,一切都很好,但在以下選擇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