Joao Pedro
Joao Pedro

Reputation: 21

formatting strings in a .txt file (C++)

unformatted_grades.txt: An image of the Unformatted Grades file

formatted_grades.txt: An image of the Formatted Grades file

I am working on an assignment where my professor wants me to open and read a .txt file with different strings inside of it. We are supposed to format the content of the file.

Ex: The read_grade_file method has a parameter int number_of_students
The first line of the file is "number_of_students 9"

I have opened and read the file and pushed each individual line into a string vector.

How do I get the number 9 in the first line by itself so I can make the number_of_students parameter equal to it??? Please help.

(We are allowed to skip over or delete any irrelevant data from the vector).

My code:

void Read_Grade_File(string names[MAX_CLASS_SIZE][2], int scores[MAX_CLASS_SIZE][MAX_NUMBER_OF_ASSIGNMENTS], int *number_of_students, int *number_of_assignments, const string input_filename) {

    string currline; // temporarily holds the content of each line read from the file
    ifstream inFile; // filestream
    vector<string> content; // vector containing each string from the file

    inFile.open(input_filename); //open the file.

    if (inFile.is_open()){
        // reads file and pushes the content into a vector
        while(!inFile.eof()){
            getline(inFile, currline);
            if(currline.size() > 0){
                    content.push_back(currline);
                }
            }
        }
        // prints the content stored in the vector
        for (int i = 0; i < content.size(); i++){
            cout << content[i] << endl;
        }

    }

Upvotes: 2

Views: 74

Answers (1)

user1118321
user1118321

Reputation: 26355

Rather than reading the entire line at once, it may make more sense to read the various values on the line as you go. For example, if you know the format of the file, then you can read the first variable's name followed by reading the value of the variable like this:

std::string variableName;
int variableValue;
inFile >> variableName;
inFile >> variableValue;

So you could get the variables whose names you know, find their values, and then loop through the rest of the file reading in that many records.

Upvotes: 1

Related Questions