2013-06-13 16 views
-1

我試圖讀取第一行(第一"\n"後)來在文件中的字符,然後將它們存儲到一個數組,但我有一個問題:每當我這樣做,我得到之後的部分,但空間('\0')被省略和字符串返回兩次!我寫了下面的代碼:
如何閱讀在c ifstream的第一行之後會發生什麼?

我加[i + 1] = '\0'使空間,但在打印輸出,這並不出現:

char out[siz]; 
string line; 
char *cv = new char[siz2]; 

while (!encdec.eof()) 
{ 
    getline(encdec, line); 
    strcpy(cv, line.c_str()); 
    while (i < siz - strlen(cv) - 1) 
    { 
     encdec >> out[i]; 
     out[i + 1] = '\0'; 
     i + 1; 
     i++; 
    } 
} 
for (int c = 0; c < strlen(out); c++) 
{ 
    cout << out[c]; 
} 

文件內容(我只是寫它隨機:d):

someone 
someone is the best man on earth and you should respect 

輸出總是這樣的:

someoneisthebestmanonearthandyoushouldrespe ctsomeoneisthebestmanonearthandyoushouldrespect

那麼有沒有什麼建議?

+0

'而(!encdec.eof())'是錯誤的。 – greatwolf

+0

''\ 0''不是空格順便說一句,這是焦炭字面空。試試''''。 – greatwolf

+0

爲什麼? (IM不是一個程序員,但就像學編程...) – afr0ck

回答

0

OK,編譯和嘗試,現在...

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

using namespace::std; 

int main() 
{ 
    char out[512]; 
    char cv[512]; 
    string line; 

    // open the file and get a line 
    std::ifstream encdec("test.txt", ifstream::in); 
    getline(encdec, line); 
    // copy the rest of the file to out 
    int i=0; 
    while (!encdec.eof()) 
    { 
    // note that the eof flag doesn't get set until get() returns it 
    out[i++] = encdec.get(); 
    } 
    // remove the eof from the stream 
    out[i-1] = 0; 
    cout << out; 
    encdec.close(); 

    return(0); 
} 
+0

NOP仍然heving一些問題..和outputing一些奇怪了8位字符:P ... – afr0ck

相關問題