2016-11-21 49 views
0

我正在寫一個字符串和一個int到一個ofstream,然後試圖用ifstream讀取它。我期望字符串被終止,所以流應該知道字符串停止的位置以及int開始的位置。但是這並沒有發生 - 當我讀回來時,它將int視爲字符串的一部分。我如何避免這種情況?C++流不能說明一個字符串結束,下一個開始?

#include <fstream> 
#include <string> 

int main() 
{ 
    std::string tempFile("tempfile.out"); 
    std::ofstream outStream(tempFile); //Tried this both with text 
    //and with ::bin but get same results 

    std::string outStr1("Hello"); 
    int outInt1 = 5; 
    std::string outStr2("Goodbye"); 

    outStream << outStr1 << outInt1 << outStr2; 
    outStream.close(); 

    std::ifstream inStream(tempFile); //Tried this both with text 
    //and with ::bin but get same results 
    std::string inStr1, inStr2; 
    int inInt1; 
    inStream >> inStr1; //this reads a string that concats all 
    //my prev values together! 
    inStream >> inInt1; //doesn't do what I want since the int was 
    //already read as part of the string 
    inStream >> inStr2; //doesn't do what I want 
} 

我該如何將字符串和int分開,而不是將它們組合成單個字符串?

+1

流中沒有字符串或整數。如果你想區分的東西,你需要設計和使用一種格式來做到這一點。逗號分隔值和XML是兩種方法。還有其他人。 –

+1

流不是一個協議,它只是一個可以發送字節的管道。 –

+0

但內存中的字符串有一個空終止符。該流不保存空終止符? – user2543623

回答

0

您可以簡單地添加新行來分隔字符串

outStream << outStr1 << std::endl << outInt1 << std::endl << outStr2; 

但爲什麼換行需要的?該字符串以空字符結尾,因此 不應該將空字符寫入字節流?如果是這樣, 那麼爲什麼需要換行符?

它不必是換行,雖然換行會爲你工作...

的std :: string並不一定是NUL終止。它有size,應該像字符數組/向量一樣對待。你可以寫NUL到流如果STR被構造爲:

std::string outStr1{'H', 'e', 'l', 'l', 'o', 0}; 

std::string s("OK"); 

構建與大小2

當您從一個流中讀取數據的字符串,它需要知道規則來提取字節並轉換爲預期的類型。基本上,如果您從流中讀取一個字符串,它需要知道何時結束字符串。簡單的規則是如果它到達一個空間(std::isspace()),則字符串終止。這裏的空間是指空格,製表符,換行符等

說,如果要提取一個整數,它應該達到一個char是不是在一個整數符號的法律,如「Z」時停止。

要充分理解這一點,http://en.cppreference.com/w/cpp/concept/FormattedInputFunction是一個良好的開端。

+1

戰術筆記:'\ n'比'std :: endl'便宜得多,因爲內置在'std :: endl'中的流清除。 – user4581301

+0

但爲什麼需要換行符?該字符串是空終止的,所以不應該C++寫入字符流的空字符?如果是這樣,那麼爲什麼需要換行符? – user2543623

相關問題