编辑:
读/写数据:
void createfile()
{
ofstream file_handle("test.txt");
if (!file_handle)
return;
//add record:
file_handle << "firstname1" << endl;
file_handle << "lastname1" << endl;
file_handle << "college1" << endl;
file_handle << "1001" << endl;
//add another record:
file_handle << "firstname2" << endl;
file_handle << "lastname2" << endl;
file_handle << "college2" << endl;
file_handle << "1002" << endl;
//remember each record is 4 lines, each field is single line
//this is the file format
}
int main()
{
createfile();
ifstream fin("test.txt");
if (!fin)
{
cout << "file not found" << endl;
return 0;
}
ofstream fout("out.txt");//note, it's a different name than input file
if (!fout)
{
cout << "cannot create new file" << endl;
return 0;
}
char buffer[1000];
while (fin)
{
cout << "attempting to read record:\n";
for (int i = 0; i < 4; i++)
{
fin.getline(buffer, 1000, '\n');
if (!fin) break;
cout << buffer << endl;//write to screen
fout << buffer << endl;//write to file
if (i == 3)
{
//buffer is expected to be a number!
int number = atoi(buffer);
//multiply by random number 2, just testing
cout << number * 2 << endl;
}
}
}
return 0;
}
只要创建一个循环,并要求输入新的文件名是否错误。
int main()
{
ifstream indata;
string fname;
for (;;)
{
cout << "enter fname, zero to exit\n";
cin >> fname;
if (fname == "0")
return 0;
indata.open(fname);
if (indata)
break;//file is valid and has been opened now
cout << "file not found, try again\n";
}
return 0;
}
所以这真的很有帮助,但它如何知道正确的文件名是什么,因为文件是一个字符串,我可以输入不同的名称,它会接受所有这些名称。我想要文件名是特定的 –
这是一个非常简单的任务。 Galik的答案完全符合作业要求。如果文件名错误,则文件不在计算机上,打开操作失败。没有别的了。如果第一次出现错误,我会提出一个更加花哨的版本,要求重新进入,现在不要担心。下一步是为'outdata'创建一个文件。这次如果文件不在计算机上并不重要,程序将创建文件并准备好写入。只要确保为'outdata'输入了不同的文件名。 –
所以我想最让我感到困惑的是,我有一个数据列表,名称院校和一个数字,我试图打开文件时输出,我不明白如何让他们输出。此外,当我有indata.open(文件)打开是红色的,不会工作 –