2016-07-01 23 views
-1

我是C++的新手,试着学会如此宽恕我犯的错误。我有一个文件,其中包含以下格式的数据:如何从文件循环输入并存储到数组变量中?

“String”,“String”,带有100个条目的字符和数字。 即“比利乔尔A 96蒂姆麦肯B70”。

我想将这些条目存储在一个类的数组中(也许我的意思是实例或对象,我对此如此不清楚)。

这是我的不良尝试: 它不好的原因它没有得到下一组学生信息......我怎么会想出一个循环来处理这个问题?所以我可以得到所有学生的名字?必须不要让100个变量输入事物infile。

#include <iostream> 
#include <string> 
#include <fstream> 

using namespace std; 


class Student{ 
private: 
    int grade; 
    char grade_letter; 
public: 
    struct Student_info(){ 
     void set_firstname(); 
     void set_lastname(); 
     string get_firstname(); 
     string get_lastname();   
    }; 


}myStudent_info; 

/// Set/get code below but left out. 

int main() 
{ 
    Student myStudent[100]; 

    ifstream myfile("input.txt"); 
    if (myfile.is_open()) 
    { 
     string a, b; 
     char c; 
     int d; 

     myfile >> a >> b >> c >> d; 
     for (int i = 0; i < 100; i++) { 
      myStudent[i].myStudentInfo.set_firstname(a); 
      myStudent[i].myStudentInfo.set_lastname(b); 
      /// the rest of variables...etc      
     } 

     myfile.close(); 
    } 
    //Exit 
    cout << endl; 
    system("pause"); 
    return 0; 
} 
+2

创建一个'Student myStudent [100]'数组来存储信息。 – user1336087

+0

'myfile >> a >> b << c << d; ''我认为'''在'c'和'd'之前是一个拼写错误。 – drescherjm

+0

'学生myStudent;'应该是'学生myStudent [100];' – drescherjm

回答

3

您只输入1位学生的数据,然后循环100次。如果你想输入的100名学生中的数据和存储每一个这是你应该做的

for (int i = 0; i < 100; i++) { 
    myfile >> a >> b >> c >> d; 
    myStudent[i].myStudentInfo.set_firstname(a); 
    myStudent[i].myStudentInfo.set_lastname(b); 
    /// the rest of variables...etc      
} 

代替

myfile >> a >> b << c << d; 
for (int i = 0; i < 100; i++) { 
    myStudent[i].myStudentInfo.set_firstname(a); 
    myStudent[i].myStudentInfo.set_lastname(b); 
    /// the rest of variables...etc      
} 
+0

也许我搞砸了,但我试图做到这一点。并在文本文件中为所有100名分配了相同的学生姓名与不同的学生姓名。 –

+0

将'Student myStudent [100];'代替'Student myStudent;'代替@drescherjm表示 –

0

什么你在正确的轨道继承人我什么,我会做的想法。但重点是你需要制作一个主要的学生矢量或数组。

class Student{ 
private: 
    int grade; 
    char grade_letter; 
    string firstname; 
    string lastname; 
public: 
     Studnet(); 
     void set_firstname(string x); 
     void set_lastname(string x); 
     void set_letter(char x); 
     void set_grade(int x);   
}; 


int main() { 
    Student x; 
    std::vector<Student> list(100); 

    sting input; 

    ifstream myfile("input.txt"); 
    if (myfile.is_open()) { 
     while(getline(myfile, input)) { 

      // divide input variable into parts 
      // use set functions to set student x's values 
      // push student x into vector of students list using "list.push_back(x);" 

     } 
     myfile.close(); 
    } 
    return 0; 
} 
+0

示例输入数据没有换行符。 –

相关问题