I'm very new to C++ so I don't know much. I have a text file that list students' first names, last names, and three grades. I want to read the values from the file into three separate arrays. The file is formatted as follows:
Bob Smith 40 42 50
Humpty Dumpty 61 66 65
Pam Bam 99 97 96
Letty Lum 99 98 99
I want to create a first array that contains the first names of the students. Then I want to create a second array that contains the last names of the students. Finally I want a third array that contains the scores of each student. I do not want to use a multidimensional array. I cannot use separators or vectors.
How can I read those specific parts of the file to their own arrays? This IS a part of a homework assignment, so I only need a hints.
What I would do is put a separator in between each group instead of spaces ex:
Bob|Smith|40 42 50
You would write this code like this (I'm going to use vectors but you use them basically the same as arrays.)
1 2 3 4 5 6 7 8 9 10 11 12
std::string temp( "" );
std::vector<std::string> first , last , grades;
std::ifstream in( "data.txt" );
while( in.good() )
{
getline( in , temp , '|' );
first.push_back( temp );
getline( in , temp , '|' );
last.push_back( temp );
getline( in , temp , '|' );
grades.push_back( temp );
}
You said you didn't want 2d but I honestly would do something like this
Thanks for the ideas! The only problem is I can't use separators or vectors for the assignment. Most suggestions I've seen for this problem involve one of the two.. so I really have no idea where to start.
#include <iostream>
#include <string>
#include <fstream>
int main()
{
constexprint MAX_STUDENTS = 1024 ; // max possible
int num_students = 0 ; // actual number
std::string first_names[MAX_STUDENTS] ;
std::string last_names[MAX_STUDENTS] ;
int first_exam_scores[MAX_STUDENTS] = {0} ;
int second_exam_scores[MAX_STUDENTS] = {0} ;
int third_exam_scores[MAX_STUDENTS] = {0} ;
std::ifstream file( "file_name.txt" ) ;
std::string first_name ;
std::string last_name ;
int one, two, three ; // scores
while( file >> first_name >> last_name >> one >> two >> three ) // for each student
{
// store the values
first_names[num_students] = first_name ;
last_names[num_students] = last_name ;
first_exam_scores[num_students] = one ;
second_exam_scores[num_students] = two ;
third_exam_scores[num_students] = three ;
++num_students ; // increment number of students
}
// ....
}
I forgot to say earlier that this was exactly what I needed! I'm always surprised by how fast the responses are here when people ask for help. Thanks! :)