i’m just beignning to learn about structs and seperating things into different files.
At the moment i have a Main.cpp file like so:
#include <iostream>
#include "StudentAnswerSheet.hpp"
using std::cout;
using std::endl;
int main(){
StudentAnswerSheet sheet = {
"Sally",
{'a', 'b', 'a', 'd', 'c'}
};
cout << sheet.studentName << ":" <<endl;
for(int i = 0; i <5; i++){
cout << sheet.studentAnswers[i] << " " ;
}
return 0;
}
and a separate header file that contains my struct StudentAnswerSheet data type:
#include <string>
using std::string;
struct StudentAnswerSheet{
string studentName;
char studentAnswers[5];
};
Ideally i’d like to be able to have an array of UP TO 5 chars to hold student answers. I think i might need to change from char to char* to get a degree of flexibility but when i tried implementing it i got an error message “too many intialisers for char [0]” and wasn’t sure how to change the sheet intialization.
I’m also not sure what the best way to go about keeping track of how many elements my array contains if i switch to an array of char*.. if i take in the student answers with cin then i can keep track of the number of answers up to 5 but if i just wanted to initialize the answers myself like i am at the moment for testing im not sure what the most efficent way to calculate the size of studentAnswers would be, so any advice on that would be much appreciate too.
Thanks for any help!
Since it seems you’re allowed to use
std::string, then why dont you usestd::vector<char>instead of usingchar[5]or thinking of usingchar*for flexibility? In your case, you can simply usestd::stringand then interpret the each character in it as student answer.Also, since
StudentAnswerSheetis not POD, which means the following would give compilation error, unless you use C++11:Here is what I would do:
then use it as: