[英]c++ File Handling error: Write and Read from same file and same program
我试图在同一个cpp程序中写入和读取文件,但我得到3个错误
conflicting decleration 'std::istream theFile'
'theFile' has a previous decleration as 'std::istream theFile'
no match for 'operator>>' 'in theFile >>n'
当你回答这个问题时,尝试更具体的菜鸟。 这是我的代码。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int n;
string name;
ofstream theFile;
istream theFile;
theFile.open("Olive.txt");
while(cin>> n>>name)
{
theFile<< n<<' '<< name;
}
while(theFile>>n>>name)
{
cout <<endl<<n<<","<<name;
}
return 0;
}
您已声明两个具有相同类型的变量。 这是不可能的。 您应该为in和outfile声明两个变量,然后打开同一个文件:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int n;
string name;
ofstream theFileOut;
ifstream theFileIn;
theFileOut.open("Olive.txt");
while(cin>> n>>name)
{
theFileOut<< n<<' '<< name;
}
theFileOut.close();
theFileIn.open("Olive.txt");
while(theFileIn>>n>>name)
{
cout <<endl<<n<<","<<name;
}
return 0;
}
请改用std :: fstream。 它可以读/写文件,并做你需要的。 因此,您将不必打开文件两次,因为您将执行ifstream和ofstream。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.