【发布时间】:2023-08-31 22:01:01
【问题描述】:
我正在向 ofstream 写入一个字符串和一个 int,然后尝试使用 ifstream 将其读回。我希望字符串以空值结尾,因此流应该知道字符串在哪里停止以及 int 从哪里开始。但这并没有发生——当我重新读回它时,它会将 int 视为字符串的一部分。我该如何避免呢?
#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 是两种方法。还有其他的。
-
流不是协议,它只是一个可以向下发送字节的管道。
-
但是内存中的字符串有一个空终止符。该流不会保存那个空终止符吗?
-
一个 std::string 可能包含嵌入的空值。这些空值将被输出。最终的空终止符是实现的一部分,但不是字符串数据的一部分,不会被输出。您需要使用某种方法来分隔流中的字段。有很多方法可以解决这个问题。
标签: c++ stream ifstream ofstream