2011-04-16 62 views
0

所以我基本上只是试图接受一些文件输入,然后把这些数据放到几个结构中。我遇到的唯一问题是指向结构体的指针。结构本身应该代表学生,我想将每个指针设置为它们的名称之一而不是任意变量。我试图以我假设的语法错误,因为它没有工作。在下面的代码中,我使用temp数组增加for循环,因为每个第四个位置都是一个新学生。关于如何去做这件事的任何想法?在C++中制作一个指向结构或对象的指针数组

#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; 
} 
+1

甜耶稣,请正确格式化您的代码(我会修复它,但在未来,缩进四个空格,使这不是每个人都完全可怕!谢谢)。 http://daringfireball.net/projects/markdown/syntax – 2011-04-16 02:46:57

+0

看起来像@peachykeen击败了我! :)干杯 – 2011-04-16 02:49:02

+1

Oooooopsy雏菊 – Sam 2011-04-16 02:49:03

回答

2

好吧,让我们从顶部开始。

你的代码是(在我重新格式化之前)一团糟。凌乱的代码很难阅读,更可能有错误。

你有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*>。矢量可以让你新的学生结构,必要时推到后面,地图将允许你根据名称密钥他们和检索后,像这样:

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

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

这是一个更好的方法处理这个问题,并且会花费很多猜测你现在正在做的事情。

1

如果你希望能够通过名称来引用的学生,可以考虑使用map<string, student>map<string, student*>

这将允许您通过students["Jack"]students["Jill"]引用个别学生。

相关问题