C++: separating first and last name from a file, separated by a comma

时间:2022-02-28 22:31:27

I have this as a file:

我有这个文件:

Collins,Bill 80
Smith,Bart 75
Allen,Jim 82
Griffin,Jim 55
Stamey,Marty 90
Rose,Geri 78
Taylor,Terri 56
Johnson,Jill 77
Allison,Jeff 45
Looney,Joe 89
Wolfe,Bill 63
James,Jean 72
Weaver,Jim 77
Pore,Bob 91 
Rutherford,Greg 42
Javens,Renee 74
Harrison,Rose 58
Setzer,Cathy 93
Pike,Gordon 48
Holland,Beth 79

As you can see the last name and first name are separated with a comma.

如您所见,姓氏和名字用逗号分隔。

Right now I have this in my code:

现在我在我的代码中有这个:

ifstream inputFile;
inputFile.open ("students.txt");

string studentNames;            // Student names - Last name followed by first
int studentMarks = 0;           // Student mark for text/exam

// Read in data from students.txt
inputFile >> studentNames;
inputFile >> studentMarks;

// IF file has too much data, output WARNING
if (numElts >= NUM_NAMES)
{
    cout << "Error: File contains too many lines of data, check the file." << endl << endl;
}
else
{
    names[numElts] = studentNames;
    marks[numElts] = studentMarks;
    numElts++;
}

I want to bypass these commas, I want to store it as firstname and then last name which then I will just merge into name like name = firstname " " last name. How should I do that, please?

我想绕过这些逗号,我想将它存储为firstname,然后将姓氏存储,然后我将合并为名称,如name = firstname“”姓氏。我该怎么办呢?拜托?

2 个解决方案

#1


0  

use this function to remove the , and get the first name last with space between,

使用此函数删除,并获得最后一个空格的名字,

    string output;
    int position = studentNames.find(',');
    for(int i=position+1;i<studentNames.size();i++)
        output+=studentNames[i];
    output+=' ';
    for(int i=0;i<position;i++)
        output+=studentNames[i];
    studentNames = output;

#2


1  

std::string::size_type commaPos = studentName.find(",");
std::string studentLastName = studentName.substr(0, commaPos);
std::string studentFirstName = studentName.substr(commaPos + 1);

#1


0  

use this function to remove the , and get the first name last with space between,

使用此函数删除,并获得最后一个空格的名字,

    string output;
    int position = studentNames.find(',');
    for(int i=position+1;i<studentNames.size();i++)
        output+=studentNames[i];
    output+=' ';
    for(int i=0;i<position;i++)
        output+=studentNames[i];
    studentNames = output;

#2


1  

std::string::size_type commaPos = studentName.find(",");
std::string studentLastName = studentName.substr(0, commaPos);
std::string studentFirstName = studentName.substr(commaPos + 1);