2013-03-26 123 views
0
firstword secondword thirdword fourthword ... 

我的文本文件包含像這樣的順序這樣的200個字,我想讀取它們並將它們複製到2D固定長度的數組中,而不需要奇怪的字符。我無法用這段代碼執行此操作:從文本文件中讀取文字C++(怪異字符)

ifstream FRUITS; 
FRUITS.open("FRUITS.TXT"); 


    if(FRUITS.is_open()) 
    { 
     char fruits1[200][LEN]; 
     int c; 

     for(c = 0; c < 200; c++) 
     { 
      char* word; 
      word = new char[LEN]; 

      FRUITS >> word; 

      for(int i = 0; i < LEN; i++) 
      { 
       fruits1[c][i] = word[i]; 
      } 
     } 
    } 

我該怎麼做?

+0

'奇怪的人物'非常具有描述性。 – 2013-03-26 22:57:13

+0

你已經提到你的代碼不能做什麼。它有什麼作用? – 2013-03-26 22:57:32

+1

LEN是最長單詞+ 1的長度嗎? – 2013-03-26 22:58:22

回答

0

如果單詞的長度小於LEN,您需要在單詞的末尾添加,這樣就不會有任何粗糙的字符。

但是,我建議使用字符串矢量作業。

#include <iostream> 
#include <fstream> 
#include <vector> 
#include <string> 

using namespace std; 
int main() 
{ 
    fstream file; 
    vector<string> v; 
    file.open("FRUITS.txt"); 
    string tmp; 
    while(!file.eof()) 
    { 
     file >> tmp; 
     v.push_back(tmp); 
    } 
    for(vector<string>::iterator i=v.begin(); i!=v.end(); i++) 
    { 
     cout << *i << endl; 
    } 
    file.close(); 
    return 0; 
} 
+1

水果>>單詞;'應該添加''\ 0'',不是嗎? – 2013-03-26 23:08:02

+0

是的,它的確如此。然後,也許他打印的數組不是字符串,而是像字符或其他東西......他沒有給我們輸出數組的代碼。 – 2013-03-26 23:20:22

0

想想這個:

FRUITS >> fruits1[c]; 

但你必須確保LEN足以容納所有char每個單詞加上'\0'

而不用擔心"=+½$#".當你做的事情如cout << fruits1[c];他們不打印。