c++ - 在 C++ 中制作指向结构或对象的指针数组

标签 c++ pointers struct

所以我基本上只是尝试获取一些文件输入,然后获取该数据并将其放入多个结构中。我遇到的唯一问题是结构指针的命名。结构本身应该代表学生,我想将每个指针设置为他们的名字之一而不是任意变量。我试图以一种我认为在语法上是错误的方式来做到这一点,因为它不起作用。在下面的代码中,我使用临时数组递增 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 .

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

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

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

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

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

这是处理此问题的更好方法,并且会消除您现在正在做的事情的大量猜测。

关于c++ - 在 C++ 中制作指向结构或对象的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5684165/

相关文章:

c - 为什么位字段的类型会影响包含结构的大小?

C++ wxwidgets 嵌套框架

c++ - 计算角度/曲率?

c++ - 将字符串解析为字符指针数组: char[0] contains the full string and [1] onward contains nothing

c++ - 64 位 T 的 std::vector<T*> 与 std::vector<T>

c - 内存问题阻止输入到结构中?

xml - 一个简单的 xml 元素如何解码为 golang 结构?

c++ - 连接两个字符串文字

c++ - const 方法中的非常量 lambda 捕获

Javascript:创建窗口的假副本以通过引用传递函数