我正在尝试将 ifstream
读入字符串,我可以在其中设置要读取的字符数。我已经阅读了 ifstream.get()
和 ifstream.getline()
的文档,但是它们都没有达到我想要的目的。
给定以下字符串:
asdfghjklqwertyuiop
我想一次读入不同数量的字符到一个字符串中。我是这样开始的,但是我得到一个错误,没有将字符串作为第一个参数的函数:
string destination;
int numberOfLettersToGet = 1;
while (inputstream.get(destination, numberOfLettersToGet)){
//Do something.
}
我可以用什么代替 inputstream.get()
?
最佳答案
您可能喜欢使用std::istream
的read
和gcount
成员函数。 get
附加一个零终止符,当您读入 std::string
时这是不必要的。
std::string destination;
int numberOfLettersToGet = 1;
destination.resize(numberOfLettersToGet);
std::streamsize n = inputstream.gcount();
inputstream.read(&destination[0], numberOfLettersToGet);
destination.resize(inputstream.gcount() - n); // handle partial read
关于c++ - 将 ifstream 的一部分读入字符串对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8425700/