我正在阅读Bjarne Stroustrup 的《Programming Principles and Practice Using C++》(第二版)。在第660-661页中,作者定义了一个函数如下:
istream& read_word(istream& is, char* buffer, int max)
// read at most max-1 characters from is into buffer
{
is.width(max); // read at most max-1 characters in the next >>
is >> buffer; // read whitespace-terminated word,
// add zero after the last character read into buffer
return is;
}
在int main()
函数中,函数被调用为read_word(cin,s,max);
,其中cin
是std::cin
,max
是一个整数,s
是一个大小为max
的字符数组。
我不理解is >> buffer;
是如何工作的。特别地,当我尝试运行代码时,那行代码会出现错误:
C2679 binary '>>': no operator found which takes a right-hand operand of type 'char *' (or there is no acceptable conversion)
这本书中没有用户定义的operator>>
或进一步的说明(除了注释)。
我想知道我们是否可以以任何有意义的方式使用类似于is >> buffer;
的东西?如果可以,它是如何工作的?还是这是书中的错误?
更新:我正在使用Visual Studio 2022。 我发现该代码在C++14/17下可以成功运行,但在C++20下无法运行。 对于clang和gcc,结果类似。