简体   繁体   English

如何将文本文件读入指针数组? (C ++)

[英]How do I read a text file into an array of pointers? (C++)

What I need to do is read a text file into an array. 我需要做的是将文本文件读入数组。 Each line has four parts; 每行包括四个部分。 first name, the ID, the height, and the weight. 名字,ID,身高和体重。 There are 13 lines in the text file, so I need to do it 13 times. 文本文件中有13行,因此我需要执行13次。 I'm going to write a loop to make it work (and will be in a function I will parse the array to.) I know how to do it with a basic array, but we're supposed to use structs for this. 我将编写一个循环以使其工作(并在将数组解析为的函数中。)我知道如何使用基本数组,但是我们应该为此使用结构。 I've looked around to try to find out how to do this, but nothing's really working for me. 我环顾四周,尝试找出执行该操作的方法,但是对我而言,没有任何真正的工作。 Here's the code I have so far. 这是我到目前为止的代码。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
struct person
{
string firstname;
int id;
double height;
double weight;
};
int main()
{
person array[13];
person *ptr;
ptr = &array[0];
ifstream inData;
inData.open("peeps.txt");
while(!inData.eof())
{
    for(ptr = &array[0]; ptr < &array[13];ptr++)
    {
        inData >> person[ptr].firstname >> person[ptr].id
        >> person[ptr].height >> person[ptr].weight;


    }
}
}

The way you're doing it is fairly messy, but it's almost correct. 您的操作方式相当混乱,但这几乎是正确的。 Inside the for loop, you're trying to index person , which is a class. for循环内,您尝试索引person ,这是一个类。 That doesn't make much sense. 那没有多大意义。 Instead, you have ptr which is pointing to each of the person objects in the array at each iteration, so you can just dereference it and assign to its members: 相反,您拥有ptr ,它在每次迭代时都指向数组中的每个person对象,因此您可以取消引用它并将其分配给它的成员:

inData >> ptr->firstname >> ptr->id
>> ptr->height >> ptr->weight;

However, even worse, you have undefined behaviour in the for loop when you do array[13] . 但是,更糟糕的是,执行array[13]时, for循环中的行为不确定。 There is no element at index 13 so you can't attempt to access it like this. 索引13处没有元素,因此您不能尝试像这样访问它。 You could change the condition to ptr <= &array[12] , but still, this is very messy. 您可以将条件更改为ptr <= &array[12] ,但这仍然很混乱。

To be clear though, you definitely don't have an array of pointers as you have said. 不过要明确一点,您绝对没有如您所说的指针数组。 Instead, you have an array of person s. 相反,您有一个person数组。

ptr = &array[0];

This takes the address of the first person in the array and assigns it to pointer. 这将获取数组中第一person的地址并将其分配给指针。 You can do this much more easily by taking advantage of array-to-pointer conversion: 您可以通过利用数组到指针的转换来更轻松地完成此操作:

ptr = array;

Also, eof() as your while criteria is often not a very good idea. 另外,将eof()用作您的while标准通常不是一个好主意。 It doesn't give a good indication of whether the next set of reads will succeed. 它不能很好地表明下一组读取是否将成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM