简体   繁体   中英

Reading First and Last Name from File

everything works when I try to read from the file when I remove the Jr. from the name . How can I read the last name as Smith Jr. using this input file? I can't use get line because that reads the whole line as the full name but how can I read the name and last name separate with last name being Smith Jr. instead of causing errors?

Intro To Computer Science c++
SAL 343
JHG 344
John Adams
111223333 100 87 93 90 90 89 91 
Willy Smith
222114444 90 73 67 -77 70 80 90 
Phil Jordan
777886666 100 80 70 -50 60 90 100

When I remove Jr. from the input file it reads the last name Smith but when I place it as Smith Jr. it doesn't read it as last name and causes huge printing errors. How can I read the last name as Smith Jr. instead of removing it? thank you here's my reading function

void Read_Student(Student & Temp , ifstream & fin){

    fin >> Temp.FirstName >> Temp.LastName ;
    fin >> Temp.Id;
    fin >> Temp.Quiz;
    for (int i = 0 ; i < 6 ; i++)
        fin >> Temp.Test[i];
    fin.ignore(10,'\n');
}
int Read_List(Student & Temp,Student List[], int Max_Size)
{
    ifstream fin;
    int i = 0;

    if (Open_File(fin))
    {
        getline(fin, List[i].Course_Name);
        getline(fin, List[i].Course_Id);
        getline(fin, List[i].Course_Location);
        Read_Student(List[i],fin);
        while(!fin.eof())
        {
            i++ ;
            if (i > Max_Size){
                cout << "\nArray is full.\n" ;
                break;
            }
            Read_Student(List[i],fin);
        }
    }
    else
    {
        cout <<"\nBad file. Did not open. Program terminated.\n";
        exit(0);
    }
    return (i);
}
fin >> Temp.FirstName >> Temp.LastName;

operator>>(istream&, string&) will stop extracting as soon as it hits a whitespace. However, you want to save the rest of the line in Temp.LastName . In this case, use std::getline instead:

fin >> Temp.FirstName;
std::getline(fin, Temp.LastName);
fin >> Temp.Id;
/* ... snip ... */

It seems like you want to treat the first word as the first name and the rest of the words as a lastname. If that's the case, you can use getline to grab a whole line, then chop the line up (I might recommend a stringstream for parsing out the individual words).

Alternatively, if you wanted to be able to parse first and last names that are multiple words, you could try adding some "delimiter" between the first and last name — like a comma. You could again use getline to get the whole line, then split between names using the comma.

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