我尝试以这种方式实现
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char b[2];
ifstream f("prad.txt");
f>>b ;
cout <<b;
return 0;
}
它应该读取2个字符,但却读取整行。这在其他语言中可以使用,但在C++中出了一些问题。
我尝试以这种方式实现
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char b[2];
ifstream f("prad.txt");
f>>b ;
cout <<b;
return 0;
}
它应该读取2个字符,但却读取整行。这在其他语言中可以使用,但在C++中出了一些问题。
您可以使用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.
3
和2
之间的关系更加明显,我建议使用一个命名常量。size_t const BufferSize = 2;
,char b[BufferSize+1] = "";
和f.read(b, BufferSize);
。 - Matthieu M.sizeof(b) - 1
(如果可能的话)。代码已更新。 - hmjdb
是一个指针,编译仍然可以通过,但在64位平台上你会得到一个固定的7
。不过,你可以使用一个用于数组的size
函数,使用模板很容易实现。 - Matthieu M.这段代码在其他语言中有效,但在C++中无法运行。
不同的编程语言之间有很多差异。特别是在这种情况下,你可能会遇到一个问题,即在C++中指针和数组几乎没有区别。该数组作为char指针传递给operator>>,被解释为字符串指针,因此它会像对待char缓冲区一样读取(直到达到宽度限制或行尾)。当发生这种情况时,你的程序应该崩溃,因为你溢出了缓冲区。
istream& get (char* s, streamsize n );