繁体   English   中英

在C ++中建立指向结构或对象的指针的数组

[英]Making an array of pointers to structs or objects in C++

因此,我基本上只是在尝试输入一些文件输入,然后将这些数据放入几个结构中。 我唯一遇到的问题是指向结构的指针的命名。 该结构本身应该代表学生,我想将每个指针设置为其名称之一,而不是任意变量。 我试图以一种我认为在语法上是错误的方式执行此操作,因为它没有用。 在下面的代码中,我使用temp数组递增for循环,因为每个第4个位置都是新学生。 关于如何解决这个问题有什么想法吗?

#include<iostream>
#include<iomanip>
#include"student.h"
#include"creditcard.h"
#include<fstream>
using namespace std;

int main ()
{
    string creditcards[20];
    int i;
    int x;
    int amount;
    string temp[20];
    ifstream infile;
    string filename;
    int count;
    int numstudents;
    string newstring="";
    string pointers[20];

    cout<<"enter the file name of which you've stored your"<<endl
        <<"credit card infomation"<<endl;

    getline(cin,filename,'\n');
    infile.open(filename.c_str());

    count=0;
    getline(infile,temp[count],'\n');
    while(! infile.eof())
    {
        count++;
        getline(infile,temp[count],'\n');          

        numstudents= (count/4);
        if(numstudents < 1 || count%4 != 0)
        {
            cout<<"incorrect data file"<<endl;
        }
    }

    cout<<numstudents<<endl;

    for(i=0,x=0; i<numstudents;i++,x+4)
    {
        student *temp[x];
        temp[x] = new student;
        pointers[i] = temp[x];
    }

    for(i=0;i<numstudents;i+4)
    {
        cout<<temp[i]<<endl;
    }

    return 0;
}

好,让我们从头开始。

您的代码(在我重新格式化之前)一团糟。 凌乱的代码更难阅读,并且更有可能出现错误。

您有3个数组,每个数组包含20个字符串。 为什么需要那么多?

其中之一被称为temp ; 必须将其用作变量名,这很好地表明您在某处处理了数据。

您是在相对较早的时候声明int count ,然后在以后将其初始化为0。 虽然不一定是一件坏事,但这并不是最好的方法(在需要时立即执行两项操作)。

您可以在一行中声明多个局部变量,但无需在函数顶部全部声明它们。 在C ++中,这不是必需的。

int main ()
{
    string creditcards[20];
    int i = 0, x = 0, amount = 0;

(合法,但可能不需要)

通常最好在需要之前同时声明和初始化变量:

int count = 0;

getline(infile, temp[count], '\n');

我记得不建议您先阅读该书,直到您达到eof为止,尽管我对此并不完全确定。 您可能需要更改此设置:

while ( !infile.eof() )
{

现在,我在这里看到的第一个实际错误是,您先读了一行,然后递增count ,然后在执行之前先读了另一行。 那是故意的吗?如果是这样,为什么有必要呢? 在循环内执行getline和递增操作将更具可读性,并且可能更可靠。

    count++;
    getline(infile, temp[count], '\n');          

我认为这行是一个错误:

 for(i=0,x=0; i<numstudents;i++,x+4)

最后一部分是i++, x+4 不会改变 x

之后的下一个循环以与x相同的方式处理i ,因此您可以将这两个结合起来。

现在,最重要的是,大规模的临时数组不能解决这个问题(或者我能想到的任何其他问题)。

要存储此类数据,您需要查看std::map<std::string, student*>std::vector<student*> 向量将允许您在必要时将新的学生结构向后推,而地图将允许您根据名称键入它们并稍后进行检索,如下所示:

typdef map<string, student*> studentmap;
studentmap students;

studentmap::iterator iter = students.find("Bob");
if ( iter != students.end() )
{
    student * bob = iter->second;
    // Work with data
}

这是处理此问题的一种更好的方法,并且将使您从现在所做的工作中获得大量的猜测。

如果您希望能够按名称引用学生,请考虑使用map<string, student>map<string, student*>

这样,您就可以通过students["Jack"]students["Jill"]来指代个别学生。

暂无
暂无

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

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