今天在学习C++读写文件时,照着书上的代码打了一遍。结果呢,编译出错了。错误如下:error C2679: binary '>>' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable conversion)。然后呢,我就去百度了,作为一个菜鸟不去百度google 就没办法活了,自己想不到解决方法只能去搜索了。找到了好多才有了解决方法,其实就是我头文件没包含。
我的代码如下:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream infile("seq_data.txt");
if( ! infile)
{
cerr << "cannt open ";
}else{
string name;
int nt;
int nc;
while(infile >> name)
{
infile >> nt >>nc;
cout << name << " "<< nc<< " " << nt <<endl;
}
}
return 0;
}
这段代码其实是读文件。seq_data.txt 文件内容如下:
tony 23 45
lucy 34 78
编译以后就一直报错,报错的代码行是while(infile >> name) 中的infile >> name。说的是没有相关的二元操作符“>>” ,就是没有重载操作符">>" ,原因是没有包含对应的头文件。在这里name是string类型的对象,所以要在头上加上#include <string> 。
其实对以基本的数据类型是没有对应的头文件的,它们是直接支持“>>","<<"等操作的,而其他的对象则需要重载这些操作符才行。因此string需要包含对应头文件,如果其他对象使用到了这些操作符也需要对应的头文件。