Reading from file to array issue

Hey, so I am working on an assignment and for part of it I need to read from a file and then put them into different array's so I can use them later. My issue is the data file has first and last name along with a test score but for some of the people they also have a middle initial. This is what I had but it didnt work since the middle initial messed it up. Here is the code


int main()
{
string a[6];
string b[6];
double c[6];
int i = 0;
ifstream theFile("student.txt");


while (!theFile.eof())
{
theFile >> a[i] >> b[i] >> c[i];
cout << a[i] << " "<< b[i]<< " " << c[i] << endl;

}
i++;
std::cin.get();
}
fyi, I highlighted my code and hit the code button by format <> but it doesnt seem to be doing it for me :( Also preview isnt showing me my post either.

So now I am trying to use getline to read the whole name and store that in a string array and the test score in a double array but I am having trouble.

Am I on the right path with using getline to accomplish this?

Here is the text file -
student.txt
Joe Doe
90
Susan F. Smith
95.5
Sam Grover
78
Diane C. Phelps
100
John Franklin
85
Derrick Myers
59
You need to split the string and take the last item returned from the split as the last name and the other stuff as the first name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <limits>
#include <iostream>
#include <string>

int main() {
    std::string line;
    float score;
    while (std::getline(std::cin, line)) {
        if (std::cin >> score) {
            // This is needed so that getline continues to work as normal
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
        
        std::string::size_type pos = line.rfind(' ');
        std::cout << "First name: " << line.substr(0, pos);
        if (pos != std::string::npos) {
            std::cout << "\nLast name: " << line.substr(pos + 1);
        }
        
        std::cout << '\n' << score << std::endl;
    }
}
Last edited on
Thank you I will try that!
Also I was wondering since the scores are on their own line would it be possible to use getline() to store each line in an array and then convert every other line (the scores) to a double from a string with stringstream? Or is it possible to use the myFile >> score[i] on every other line since that line would only have the score?
why i is out the loop scope ?
Topic archived. No new replies allowed.