我知道解决类似这样的问题在这里有很多问题,但在搜索了一段时间之后,我找不到帮助我的答案,所以希望我不会问一些已经回答了一百万次的问题之前。
我有一个看起来像这样的文本文件:
1 14 100
3 34 200
2 78 120
第一个数字是ID号,第二个是Age,第三个数字是Weight。 (这些是任意描述)我也有一个如下所示的结构:
struct myData{
int ID;
int age;
int weight;
};
在创建myData结构数组之后,如何遍历文本以便最终在数组的一个索引中最终得到文本文件每行的每个元素?例如,在使用文本文件的元素填充数组后,我应该能够说
cout << myData[0].ID << ", " << myData[0].age << ", " << myData[0].weight << "\n";
它应该打印出“1,14,100”,如果索引在上面的代码行中是2,它应该打印出“3,78,120”。我已经尝试过使用getLine()或get()以及类似的东西寻找其他人的例子,但我似乎无法掌握它。我希望我能够提供有关我的问题的足够信息,以便本网站上的向导可以轻松回答。提前谢谢!
答案 0 :(得分:4)
这样的事情怎么样:
struct myData
{
int ID;
int age;
int weight;
// Add constructor, so we can create instances with the data
myData(int i, int a, int w)
: ID(i), age(a), weight(w)
{}
};
std::vector<myData> input;
std::ifstream file("input.txt");
// Read input from file
int id, age, weight;
while (file >> id >> age >> weight)
{
// Add a new instance in our vector
input.emplace_back(id, age, weight);
// Skip over the newline, so next input happens on next line
std::ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
// Close the file after use
file.close();
// Print all loaded data
for (auto data : input)
{
cout << "ID: " << data.ID << ", age: " << data.age << ", weight: " << data.weight << '\n';
}
答案 1 :(得分:1)
您可以使用包含文件:
#include <fstream>
并简单地做类似的事情
std::ifstream infile("file.txt");
int a, b, c;
while (infile >> a >> b >> c)
{
// process (a,b,c)
}
不要忘记关闭流。
答案 2 :(得分:0)
打开文件并浏览它以读取所有行:
//Opening File
FILE *trace;
trace=fopen("//path//to//yourfile","r");
// Read the file
myData list[N];
int count=0;
while(!feof(trace)){
fscanf(trace,"%d %d %d\n", &myData[count].ID, &myData[count].age, &myData[count].weight);
count++;
}
// now you have an array of size N go through it and print all
for(int i=0; i<count; i++)
printf("%d %d %d\n", myData[i].ID, myData[i].age, myData[i].weight);