2014-03-05 127 views
1

因此,我正在为我的CS162类做一个家庭作业,这需要我编写一个程序,允许用户输入他们的大学课程计划。用户输入他们已经采取,正在采取和/或计划采取的课程,其类别为:部门/班级编号,班级名称,学期/年份,班级是否为其专业所需,以及任何额外注释。然后,该程序应该将这个信息存储在外部数据文件中,以便这些类存储并不会丢失。该程序应该能够在内存中存储多达60个类。在C++的外部文件中存储结构数组

我知道如何创建结构数组,我知道外部文件背后的基础知识,但我想我在组合这两个时遇到了困难(我是一个新手,很抱歉,如果这真的很基础!)

这是我到目前为止有:

struct college_class 
{ 
    char dept_classnumber; 
    char class_name; 
    char term_year; 
    char is_required; 
    char comments; 
    char grade; 
} 

college_class[60] 

int main() 
{ 
    int n; 
    char again; 
    for(n=0;n<60;n++) 
    { 
     do 
     { 
      cout<<"Enter department and class number (e.g. CS162): "; 
      getline (cin,college_class[n].dept_classnumber); 
      cout<<"Enter class name (e.g. Intro to Computer Science): "; 
      getline (cin,college_class[n].class_name); 
      cout<<"Enter the term and year the class was/will be taken: "; 
      getline (cin, college_class[n],term_year; 
      cout<<"Enter whether or not this class is required for your major: "; 
      getline (cin,college_class[n],is_required); 
      cout<<"Enter any additional comments here: "; 
      getline (cin, college_class[n],comments); 
      cout<<"Would you like to enter another class?(y/n)"; 
      cin>>again; 
     } 
     while(again == 'y' || again == 'Y' && i<60) 
    } 

这是在获取用户输入的条件朝着正确的方向?我的另一个问题是,如何将外部文件合并到此文件中,以便用户输入的所有内容都存储在文件中?对不起,如果这有点含糊,我显然不是在寻找我为我做的功课 - 我只是想找一个方向从这里开始。

我知道,写在一个文本文件看起来像这样,例如:

ofstream my file ("example"); 
if(myfile.is_open())) 
{ 
    myfile <<"blah blah blah. \n"; 
    myfile.close(); 
} 

...我只是不知道如何使这项工作对于结构的阵列。

+0

'struct class' this is valid?我从来没有尝试过,但我期望编译器错误。在这里输入部门和班级号码(例如“CS162”):“''''''''''''''''''''''''''''''''你应该在字符串中跳过那些引号,比如'”输入部门和班级编号(例如\“CS162 \”)如何处理文件?然后展示你尝试过的东西。 –

+0

@MariusBancila:[不,这不是](http://coliru.stacked-crooked.com/a/d12860e784b6f577)。 'class'是一个关键字,不能用作标识符。 –

+0

这就是我所说的...... :) –

回答

1

你的代码有很多错误。 首先,你必须为你的college_class数组创建一个变量。 例如:

college_class myCollegeClass[60] 

和使用要求输入

getline (cin, myCollegeClass[n].term_year;) 

当你不小心用逗号某些线路出现,注意是

此外,焦炭只能容纳一个字符,如果你想保存完整的类名,这将是不够的,在你的结构中使用字符串。

struct college_class 
{ 
    string class_name; 
    ... 
} 

您使用了嵌套循环出现,这将重复你的问题60次,不管你说你不想输入任何东西。

我建议

int i=0; 
char again = 'y'; 
while(again != 'n' && again != 'N' && i<60) 
{ 
    ... 
    i++ 
} 

至于该文件,你有你的投入,只是循环虽然你myCollegeClass阵列后的数据写入到文件中。例如:

myfile << myCollegeClass[i].class_name; 
+0

谢谢!这正是我需要开始的。 – hhoward