我正在执行一个程序,该程序应该从文本文件中提取行并逐行读取它们。我的程序在第一行工作良好,但是停止并且不读取后三行。这是我到目前为止的代码:
ifstream inputfile;
ofstream outputfile;
inputfile.open("test.txt");
outputfile.open("invoice.txt");
while (!inputfile.eof())
{
inputfile >> cust_id;
inputfile >> title;
inputfile >> author;
inputfile >> isbn;
inputfile >> isbn2;
inputfile >> isbn3;
inputfile >> isbn4;
inputfile >> price;
inputfile >> quanity;
inputfile >> type;
inputfile >> genre;
outputfile << "____________________________________________________________________________________________________________" << endl;
outputfile << "Invoice" << endl;
outputfile << " " << endl;
outputfile << "Customer ID: " << cust_id << endl;
outputfile << title << " " << fiction_type << " " << genre_type << " " << quanity << "@" << price << " " << "subtotal: " << subtotal << endl;
outputfile << " " << endl;
outputfile << "Total book sales: " << subtotal << endl;
outputfile << "Tax: " << totaltax << endl;
outputfile << "Subtotal: " << subtotal_withtax << endl;
outputfile << "Fee: " << fee << endl;
outputfile << "Total: " << total_price << endl;
cout << "something" << endl;
inputfile.close();
return 0;
}
我已经删除了部分代码,因为它不是必需的,它只是使用不同的if / elif循环来验证数据。
我尝试读取的文件是:
234 Dog_Strategy Henry_Moreno 3-598-21500-2 12.99 5 N M
6789 Companion_Kicked_Me_Out Lorraine_Johnson 3-598-21599-1 24.99 3 F R
3444 Mime_On_My Journey Kristy_Wahl 3-699-21500-8 6.75 10 N D
4455 Damaged_By_The_Joke Henry_Christopher 3-598-21500-2 12.99 4 N R
当我执行代码时,它可以完美地完成第一行,但不会读取最后三行,因此我无法弄清原因。任何帮助都是极好的。
答案 0 :(得分:-1)
ifstream inputfile;
ofstream outputfile;
inputfile.open("test.txt");
outputfile.open("invoice.txt");
while (!inputfile.eof())
{
inputfile >> cust_id;
inputfile >> title;
inputfile >> author;
inputfile >> isbn;
inputfile >> isbn2;
inputfile >> isbn3;
inputfile >> isbn4;
inputfile >> price;
inputfile >> quanity;
inputfile >> type;
inputfile >> genre;
outputfile << "____________________________________________________________________________________________________________" << endl;
outputfile << "Invoice" << endl;
outputfile << " " << endl;
outputfile << "Customer ID: " << cust_id << endl;
outputfile << title << " " << fiction_type << " " << genre_type << " " << quanity << "@" << price << " " << "subtotal: " << subtotal << endl;
outputfile << " " << endl;
outputfile << "Total book sales: " << subtotal << endl;
outputfile << "Tax: " << totaltax << endl;
outputfile << "Subtotal: " << subtotal_withtax << endl;
outputfile << "Fee: " << fee << endl;
outputfile << "Total: " << total_price << endl;
cout << "something" << endl;
}
inputfile.close();
return 0;
您必须关闭文件并在循环后返回,否则程序将在一次迭代后退出。