我想从键盘获取用户输入(整数值)并将其写入文件中。然后,选择18-80的值并写入另一个文件。我的程序运行直到键盘输入并将它们写入文件。但我不知道如何在条件下选择一些值并将它们写在另一个文件中。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream age;
age.open("age.txt",ios::out);
cout<<"Input the ages from keyboard: "<<endl;
for(int i=0;i<3;i++)
{
int n;
cin>>n; //value inputted from keyboard
age<<n<<endl;
}
ifstream agein;
agein.open("age.txt"); //Reading that existing file
ofstream ageout;
ageout.open("information.txt"); //writing in another file
{
int m;
if(m>18 && m<=80) //picking value from 18-80
ageout<<m<<endl;
}
age.close();
agein.close();
ageout.close();
return 0;
}
答案 0 :(得分:0)
即使您从读/写切换,也不要忘记在重新打开文件之前关闭文件 你走了:
using namespace std;
int main()
{
ofstream age;
age.open("age.txt", ios::out);
cout << "Input the ages from keyboard: " << endl;
for (int i = 0;i<3;i++)
{
int n;
cin >> n; //value inputted from keyboard
age << n << endl;
}
age.close();// Do NOT forget that before reopening it
ifstream agein;
agein.open("age.txt"); //Reading that existing file
ofstream ageout;
ageout.open("information.txt");//writing in another file
if(ageout)//Checks if the file exists
{
string str;
int m;
while (agein >> m) //Get an int from a file
if (m>18 && m <= 80) //picking value from 18-80
ageout << m << endl;
}
agein.close();
ageout.close();
return 0;
}