如何使用 fstream 的 .get 字符串?

How to use string for .get using fstream?

本文关键字:字符串 get 何使用 fstream      更新时间:2023-10-16

我需要使用字符串而不是字符来一次写入多个字符。

我希望第一个周期从文件中获取数据,第二个周期通过string周期来因为将来我想一次接收 2 或 4 个字符。

我可以实现这一点以使.get通过string工作吗?

fstream fs("file.txt", fstream::in | fstream::out | ios::binary);
for (string i; fs.get(i);) {
cout << i;    
}

带有 c 字符串的istream::get最多读取 n 个字符,或者一个分隔符,默认换行符(与istream::getline非常相似,但它将分隔符保留在流中,而getline使用它(。

读取固定长度的块,不管有istream::readistream::gcount说实际读取了多少。不幸的是,两者都没有专门针对std::string的重载,主要的缺点是必须首先调整字符串的大小(从而初始化(。

将它们放在一起,您可以得到类似的东西:

std::string buffer;
std::fstream is("file.txt", std::ios::in | std::ios::binary);
while (is)
{
buffer.resize(128); // Whatever size you want
is.read(buffer.data(), buffer.size()); // Read into buffer, note *does not null terminate* // C++17
//is.read(&buffer[0], buffer.size()); // Older C++
buffer.resize(is.gcount()); // Actual amount read. Might be less than requested, or even zero at the end or a read failure.
std::cout << "Read " << buffer.size() << " characters." << std::endl;
std::cout << buffer << std::endl;
}

具体来说getline,有std::getline为您处理std::string

std::string buffer;
std::fstream is("file.txt", std::ios::in | std::ios::binary);
while (std::getline(is, buffer))
{
std::cout << "Line: " << buffer << std::endl;
}

请注意,getgetline都可以使用其他分隔符,因此它不必是"行"。