2016-07-05 136 views
-1

我有一個名爲firstFileStream[50]的char數組,它使用fstream從infile寫入。如何將char數組轉換爲C++中的字符串?

我想將此char數組轉換爲名爲firstFileAsString的字符串。如果我寫string firstFileAsString = firstFileStream;它只寫入數組中的第一個單詞並停在第一個空格或空字符處。如果我寫firstFileAsString(firstFileStream)我得到相同的輸出。

我該如何寫整個字符數組,以便將字符串中的所有單詞寫入字符串?

下面是代碼的讀取和寫入:

string firstInputFile = "inputText1.txt"; 
char firstFileStream[50]; 

ifstream openFileStream; 
openFileStream.open(firstInputFile); 

if (strlen(firstFileStream) == 0) { // If the array is empty 
    cout << "First File Stream: " << endl; 
    while (openFileStream.good()) { // While we haven't reached the end of the file 
     openFileStream >> firstFileStream; 
    } 
    string firstFileAsString = firstFileStream; 

} 
+0

你怎麼知道有多少個字符複製? – juanchopanza

+0

輸入文件的設置長度包含該字符數,包括空格 – fauliath

+0

@Magis您的意思是你需要複製50個字符,還是一些祕密數字? – juanchopanza

回答

0

我的問題,因爲zdan指出的是,我只是讀取文件的第一個字,所以不是我用istreambuf_iterator<char>分配內容直接到字符串而不是字符數組。然後可以將其分解爲字符數組,而不是其他方式。

0
openFileStream >> firstFileStream; 

只讀取文件中的一個字。

的讀取整個文件(至少到緩衝能力)一個簡單的例子是這樣的:

openFileStream.read(firstFileStream, sizeof(firstFileStream) - 1); 
// sizeof(firstFileStream) - 1 so we have space for the string terminator 
int bytesread; 
if (openFileStream.eof()) // read whole file 
{ 
    bytesread = openFileStream.gcount(); // read whatever gcount returns 
} 
else if (openFileStream) // no error. stopped reading before buffer overflow or end of file 
{ 
    bytesread = sizeof(firstFileStream) - 1; //read full buffer 
}  
else // file read error 
{ 
    // handle file error here. Maybe gcount, maybe return. 
} 
firstFileStream[bytesread] = '\0'; // null terminate string 
相關問題