-2

I have 3 different text files.

P6_in1.txt
4 4 2
Max Key 10 10 10 10 20 20 20 20 100 100
Franklin Ben 10 10 10 10 20 20 20 20 100 100
Washingtonian George 10 10 0 10 20 0 0 20 100 80

P6_in2.txt
3 3 3
Key Max 15 10 15 20 30 30 60 100 80

P6_in3.txt
2 6 2
Solution Key 10 10 10 10 20 20 20 20 100 100
Washington George 10 10 10 10 20 20 20 20 100 100
Jefferson Thomas 10 0 8 6 20 15 13 0 80 90
Franklin Benjamin 0 0 0 0 20 10 20 10 100 50
Lincoln Abraham 10 5 10 5 0 0 0 0 80 30
Madisonville James 5 7 9 3 10 12 14 16 0 0
Wilson Woodrow 2 4 6 8 10 12 14 16 74 89
Hoover Herbert 0 10 10 10 0 20 20 20 0 100
Roosevelt Franklin 0 0 0 0 0 0 0 0 0 0

I need to write a program that works for all 3 which reads in all this information. It skips the first line and then assigns each name to a variable and each number to a variable so later i can use those variables to do some simple math. Ill also have to format it something like this but im just not sure how to read each name and number in and assign them to a variable. enter image description here

thunkster
  • 1
  • 1
  • 2
    Take advantage of the fact that the first line is always the same and the remaining lines appear to follow a similar format. Use `std::vector` to manage the unknown number of items if they have to be stored. Use [Option 2 in this linked answer](https://stackoverflow.com/a/7868998/4581301) as the basis of your parser. – user4581301 Mar 01 '22 at 19:44
  • 2
    Recommendation: don't ask a Stack Overflow about how to write code without showing an attempt at writing the code. Even if what you tried is completely wrong it A) shows that you did something, and often that attempt is what separates your question from the horde of other questions Stack Overflow users see every day and B) a good answerer will see where the program goes awry, explain the problem, and show you how to avoid similar mistakes in the future. – user4581301 Mar 01 '22 at 19:48

1 Answers1

1

A good technique is to model a class or struct to one record or text line.

struct Student
{
    std::string first_name;
    std::string last_name; 
    std::vector<unsigned int> grades;
};

Next, overload operator>> to read in the structure:

struct Student
{
    std::string first_name;
    std::string last_name; 
    std::vector<unsigned int> grades;
    friend std::istream& operator>>(std::istream& input, Student& s);
};
std::istream& operator>>(std::istream& input, Student& s)
{
    input >> s.first_name;
    input >> s.last_name;
    std::string text_line;
    std::getline(input, text_line);
    std::istringstream text_stream;
    unsigned int grade = 0;
    while (text_stream >> grade)
    {
        r.grades.push_back(grade);
    }
    return input;
}

With the above code fragment, you could read a file:

//...
unsigned int a, b, c;
//...
my_file >> a >> b >> c;
std::vector<Student> classroom;
Student s;
while (my_file >> s)
{
    classroom.push_back(s);
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154