简体   繁体   中英

C++ Assigning words from file input to strings or ints

I need to open a file in this format

Firstname Lastname 1 2 3 4 5

Firstname Lastname 2 3 4 5 6

I need to assign the first name of a line to a member array of structs and last name of the line to another member of the struct and each number of the line to a array of scores in the struct and each new line goes to the next index of the struct array, doing the same thing (Sorry if I worded that badly).

I'm not too worried about the score assignment I have an idea of how to do that but right now I'm trying to use getline to assign each word at a time to the strings inside the structs but when I run the code, it skips the first line and inputs the first and last name of the second line and I can't figure out how to make it start with the first line.

Here is my code

ifstream fin;
fin.open("Scores.txt");
if (!(fin.is_open()))
    cout << "Failed to open file.\n";

if (stuCount < 10)
{
    for (int n = 0; !fin.eof();)
    {
        for (string line[10]; getline(fin, line[n]); n++)
        {
            fin >> students[stuCount].fname >> students[stuCount].lname;
            stuCount++;
            cout << line[n] << endl;
        }
    }
}

Your problem is that both getline and the (>>) operator are advancing the position of the read buffer in the stream. You need to buffer your call to getline.

An idea for changing your code up would be this:

ifstream fin("Scores.txt", ifstream::in);
if (!fin.is_open()) {
cout << "Failed to open file." << endl;
    return -1;
}

if (stuCount < 10)
{
    while (!fin.eof())
    {
        string line;
        getline(fin, line);
        stringstream ss(line);
        ss >> students[stuCount].fname >> students[stuCount].lname;
        cout << line << endl;
        stuCount++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM