我正在寫一個字符串和一個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分開,而不是將它們組合成單個字符串?
流中沒有字符串或整數。如果你想區分的東西,你需要設計和使用一種格式來做到這一點。逗號分隔值和XML是兩種方法。還有其他人。 –
流不是一個協議,它只是一個可以發送字節的管道。 –
但內存中的字符串有一個空終止符。該流不保存空終止符? – user2543623