2016-03-12 66 views
0

我希望为读取变量输出不同的字符串。例如,下面,我希望打印在读取之前输入英文标记英文标记使用eng.setmarks()。请建议一种方法来实现这一点。打印读取不同对象变量的不同字符串

这里是我的代码:(看下面循环)

#include <iostream> 
#include <cstring> 

using std::cin; 
using std::cout; 

class student { 
    char name[20]; 
    int age; 

    class marks { 
     int marks; 
     public: 
      void setmarks(int x) { 
       marks = x; 
      } 
      int getmarks() { 
       return marks; 
      } 
    }; 

    public: 
     marks eng, math, phy, chem, cs; // nested objects are public 

     void setname(char* n) { 
      strncpy(name, n, 20); 
     } 
     char* getname() { 
      return name; 
     } 
     void setage(int a) { 
      age = a; 
     } 
     float total() { 
      size_t total = eng.getmarks() + math.getmarks() + 
      phy.getmarks() + chem.getmarks() + cs.getmarks(); 

      return total/500.0; 
     } 
}; 

int main() {a 
    student new_stud; 


    char temp[20]; 

    cout << "Enter name: "; 
    cin >> temp; 
    cin.get(temp, sizeof(temp)); 
    new_stud.setname(temp); 

    int age; 

    cout << "Enter age: "; 
    cin >> age; 
    new_stud.setage(age); 

    for(size_t i = 0; i < 5; ++i) { 
     // I wish to output: "Enter marks in" + subject_name, but harcoding it seems tedious 
    } 

    cout << "\nTotal Percentage: " << new_stud.total(); 

    return 0; 
} 
+0

对不起,我不明白你在问什么?你能否更精确地阐述它。 – surajsn

+0

我的意思是这些单词不会被写入,例如当我阅读不同的主题标记时,我必须明确地写出*“输入英文标记:”并阅读标记。所以如果没有科目很大,那就成了头痛的问题。我认为** Marci **已经给出了很好的解决方案! – samjoe

回答

1

所以,如果我理解正确的话,你想打印出你将要读入变量的名称。现在,这不能在你想要的方式上完成。你可以做的最好的事情是创建一个主题名称数组和一个标记数组。

string[5] Subjects = {"Maths", "English", "Chemistry", "Physiscs", "Computer Sciences"}; 
marks[5] Marks; 
for(int i=0;i<5;i++) { 
    cout << "Please enter marks in " << Subjects[i] << ":" << endl; 
    int a; 
    cin >> a; 
    Marks[i].setmarks(a); 
} 

您也可以使马克类有一个字段主题名称,并给它一个函数inputfromuser(),就像这样:

class marks { 
    int marks; 
    string subjectName; 
    public: 
    void setmarks(int x) { 
    marks = x; 
    } 
    int getmarks() { 
    return marks; 
    } 
    void inputfromuser() { 
    cout << "Please enter marks in " << subjectName << ":" << endl; 
    cin >> marks; 
    } 
}; 

对不起使用我的std ::字符串类型,我对生成的char []处理文本的方式不太舒服。

+0

我认为这是唯一的方法,非常感谢你! – samjoe

相关问题