我有这个文件:

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


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

现在我的代码中有这个:

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++;
}


我想绕开这些逗号,我想将其存储为名字,然后是姓氏,然后我将它们合并成name = firstname " " last name之类的名字。请问该怎么办?

最佳答案

使用此功能删除,并获得姓氏,中间用空格隔开,

    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;

关于c++ - C++:使用逗号分隔文件中的名字和姓氏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22852101/

10-12 05:11