【发布时间】:2017-06-09 23:38:29
【问题描述】:
我正在尝试从格式与此类似的文本文件中读取数据:
knife, object, 0
bag, object, 15
kitchen, room, 400
放入由结构组成的数组。这是我目前所拥有的,但它只读取第一个元素然后返回垃圾。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct itemlist
{
string type;
string selltype;
int price;
int diditsell=0;
};
int main()
{
string filename;
cout << "Please enter a file name. " << endl;
cin >> filename;
ifstream in(filename);
itemlist c[100];
for (int i=0;i<100;i++)
{
in >> c[i].type >> c[i].selltype >> c[i].price;
cout << c[i].type << endl;
cout << c[i].selltype << endl;
cout << c[i].price << endl;
}
}
我试图找到特别适合我正在尝试做的示例,但实施它们并没有解决问题。任何帮助将不胜感激。
【问题讨论】:
-
检查读取是否成功:
if (in >> c[i].type >> c[i].selltype >> c[i].price) { print stuff; } else { handle error; } -
哦,等一下!您需要解析逗号和空格吗?呸。这需要
std::getline (in, c[i].type, ',');和一些额外的代码来分割空间。 -
如果文件中的文件少于 100,您不想全部读取 100。你可以使用
std::vector吗? -
@user4581301 我被指示创建一个 100 的大小。使用 std::vector 似乎没有任何问题,但我的 C++ 技能不是很熟练。