试图弄清楚如何制作一个小的库存程序,但我终生无法弄清楚为什么它不起作用。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct record
{
int item_id;
string item_type;
int item_price;
int num_stock;
string item_title;
string item_author;
int year_published;
};
void read_all_records(record records[]);
const int max_array = 100;
int main()
{
record records[max_array];
read_all_records(records);
cout << records[2].item_author;
return 0;
}
void read_all_records(record records[])
{
ifstream invfile;
invfile.open("inventory.dat");
int slot = 0;
for (int count = 0; count<max_array; count++);
{
invfile >> records[slot].item_id >> records[slot].item_type >> records[slot].item_price >> records[slot].num_stock >> records[slot].item_title >> records[slot].item_author >> records[slot].year_published;
slot++;
}
invfile.close();
}
我正在通过让它打印来自记录作者的第二个项目来测试它。当我运行它时,它根本不显示作者姓名。 .dat 文件几乎位于项目所在的每个文件夹中(我忘记了它需要位于哪个文件夹中),所以它就在那里。 问题不在于文件不工作。这是阵列不打印任何东西。 我的 inv 文件基本上是:
123456 书 69.99 16 标题 ETC 等等
并在一行中重复不同的书籍/CD 等,全部没有空格。应该就在下一个。
最佳答案
您应该检查文件是否已打开。
invfile.open("inventory.dat");
if (!invfile.is_open())
throw std::runtime_error("couldn't open inventory file");
您应该检查您的文件读取是否正常,并在您到达文件末尾时中断。
invfile >> records[slot].item_id >> records[slot].item_type ...
if (invfile.bad())
throw std::runtime_error("file handling didn't work");
if (invfile.eof())
break;
您可能想一次读取每条记录,因为从这段代码中不清楚 C++ 流应该如何区分每个字段。
通常您会期望使用 std::getline
,根据您分隔的方式拆分字段,然后使用类似 boost::lexical_cast
的方法来执行类型解析。
关于c++ - 对于循环和输入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9899822/