I am currently trying to do an assignment, and having a few problems. i am fairly new to C++ so i apologize if this is a stupidly easy question.
the task was to create a file that would read in from a .txt file a list of student names and the marks they received, then print it out in a certain way. i have managed to get it to read a specified file, but i'm stuck trying to separate the names of the students from the marks they received.
here is an example of what the text file being read in looks like:
David Nagasake 100 85 93 89
Mike Black 81 87 81 85
Andrew Van Den 90 82 95 87
.
is there an easy way to split the names from the marks?
I would recommend using std::string rather than a char array:
1 2 3 4 5 6 7 8 9 10 11 12 13
std::string word; // better than char word[100];
myFile >> numRecords;
cout << numRecords << endl;
myFile.ignore(10, '\n');
for(int i=0; i < numRecords; i++)
{
// myFile.getline(word, 100, '\n'); // Rather than useing this...
std::getline(myFile, word); // ...use this instead to read a std::string
cout << word << endl;
// word[0] = '\0'; // No need to wory about this now
}
is there an easy way to split the names from the marks?
Yes. C++ allows you to not only extract strings from files, but also floating-point numbers, whole numbers, characters, etc. Consider this code sample:
In this example, I extract 2 pieces of data; a string and an integer. Notice how each field is extracted individually. Each field is delimited by white-space, meaning that the data within the field ends when white-space is encountered.
Thank you all for the advice, been really helpfull!
i think i should be ok from now on, and its especially good because i understand exactly what you were suggesting, so hopefully i will be able to remember all this the next time i need to do this.