c++ - 将 ifstream 的一部分读入字符串对象?

标签 c++ string input stream

我正在尝试将 ifstream 读入字符串,我可以在其中设置要读取的字符数。我已经阅读了 ifstream.get()ifstream.getline() 的文档,但是它们都没有达到我想要的目的。

给定以下字符串:

asdfghjklqwertyuiop

我想一次读入不同数量的字符到一个字符串中。我是这样开始的,但是我得到一个错误,没有将字符串作为第一个参数的函数:

string destination;
int numberOfLettersToGet = 1;

while (inputstream.get(destination, numberOfLettersToGet)){
   //Do something.
}

我可以用什么代替 inputstream.get()

最佳答案

您可能喜欢使用std::istreamreadgcount 成员函数。 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/

相关文章:

C 控制台输入

python - 如何根据条件替换 pandas 列中的字符串?

android - 第一次单击时,Android App不会录制声音

C++ 错误 : invalid Operands of types 'double' and <unresolved overloaded function type' to binary 'operator'

c++ - 如何从 cv::Mat 访问数据

c++ - Apache 有适用于 windows 和 linux 的共享对象。他们是怎么做到的?

c - 通过指针传递字符串 - 不兼容的参数

javascript - 用本地镜像填充 svg 元素

javascript - 从输入表单中删除 HTML 标签输入

c++ - 将特征矩阵转换为 std::vector<std::array<>> 形式