如何从文本文件中读取特定数量的字符

use*_*967 7 c++ string file char

我试着这样做

 #include <iostream>
 #include <fstream>

using namespace std;

int main()
{
    char b[2];
    ifstream f("prad.txt");
    f>>b ;
    cout <<b;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它应该读取2个字符,但它读取整行.这适用于另一种语言但由于某种原因无法在C++中运行.

hmj*_*mjd 9

您可以使用read()指定要读取的字符数:

char b[3] = "";
ifstream f("prad.txt");

f.read(b, sizeof(b) - 1); // Read one less that sizeof(b) to ensure null
cout << b;                // terminated for use with cout.
Run Code Online (Sandbox Code Playgroud)

  • 为了使 `3` 和 `2` 之间的关系更加明显,我建议使用命名常量。`size_t const BufferSize = 2;`, `char b[BufferSize+1] = "";` 和 `f.read(b, BufferSize);` (2认同)