中易网

怎么用c++从文件读取数据

答案:2  悬赏:0  
解决时间 2021-02-02 05:59
#include <fstream.h>
#include <iostream.h>
main(){
fstream file1;
file1.open("123.txt",ios::in|ios::out,0);
file1<<"hello!"<<endl<<"ok";
CString str;
file1>>str;
cout<<str;
return 0;
}

用vc6编译如上程序为什么提示:error C2678: binary '>>' : no operator defined which takes a left-hand operand of type 'class fstream' (or there is no acceptable conversion)
Error executing cl.exe.
最佳答案
//用我这个就行了

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

void main()
{
fstream file1;
file1.open("123.txt",ios::in|ios::out|ios::trunc); //标志位不加trunc的话,文件不存在就没办法创建
if(!file1.is_open())
{
cout<<"file not open"<<endl;
return;
}
file1<<"hello!"<<endl<<"ok";
string str; //不是mfc程序就不要用mfc里面的类了
file1.seekp(ios::beg); //不把文件指针定到文件头你是不会读到东西的,因为刚才往文件里写东西已经把文件指针指到文件末尾了
file1>>str;
cout<<str;
}
全部回答
#include #include #include using namespace std; int main() { string name,number;//存储姓名和学号的临时变量 ifstream in("luo.txt"); if(in) { while(!in.eof()) { in>>name>>number; //此时姓名和学号已经读取到了name和number中 cout<
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯