2011-10-02 51 views
0

在C++中,如何將文件內容讀入字符串數組?我需要這個對於由對用空格分隔字符的如下文件:將filecontent對的字符讀入數組

cc cc cc cc cc cc 
cc cc cc cc cc cc 
cc cc cc cc cc cc 
cc cc cc cc cc cc 

C可以被任何字符,包括空間!嘗試:

ifstream myfile("myfile.txt"); 
int numPairs = 24; 
string myarray[numPairs]; 

for(int i = 0; i < numPairs; i++) { 
    char read; 
    string store = ""; 

    myfile >> read; 
    store += read; 

    myfile >> read; 
    store += read; 

    myfile >> read; 

    myarray[i] = store; 
} 

問題是,這只是跳過空格alltogether,因此導致錯誤的值。我需要改變什麼以使其識別空間?

回答

2

這是預期的行爲,因爲operator>>默認情況下會跳過空格。

解決方案是使用get方法,該方法是一種低級操作,可從流中讀取原始字節而不進行任何格式化。

char read; 
if(myfile.get(read)) // add some safety while we're at it 
    store += read; 

順便說一下,在C++中,VLAs(具有非常量大小的數組)是非標準的。您應該指定一個常量大小,或者使用容器,如vector

1

如果輸入的是精確的像你說下面的代碼將工作:

ifstream myfile("myfile.txt"); 
int numPairs = 24; 
string myarray[numPairs]; 

EDIT: if the input is from STDIN 
for(int i = 0; i < numPairs; i++) { 
    myarray[i] = ""; 
    myarray[i] += getchar(); 
    myarray[i]+= getchar(); 
    getchar(); // the space or end of line 

} 

EDIT: If we don't now the number of pairs beforehand 
     we shoud use a resizable data structure, e.g. vector<string> 
vector<string> list; 
// read from file stream 
while (!myfile.eof()) { 
    string temp = ""; 
    temp += myfile.get(); 
    temp += myfile.get(); 
    list.push_back(temp); 
    myfile.get(); 
} 
+0

大。現在,如果我事先不知道對的數量呢? – Ben

+0

謝謝你的回答,最後一個問題:你使用矢量的方式,它會一直調整大小,不是嗎?我最終將使用的文件包含的內容比我用於該示例的24對還多,因此在讀取對之前是否有自動確定所需大小的方法? (另外,我在程序中需要的是文件中「列」和「行」的數量 - 我想我可以使用與myfile.get()相關的列的計數器,並使用手動檢查\ n對於rowcounter - 但是在讀對之前,事先如何?) – Ben

+0

永遠不要在'eof'上循環。只需測試流本身:'while(myfile)'。 –