我正在尝试编写一个程序,该程序将打开用户输入文件名,然后在该文件中获取名称,并将它们从LastName,FirstName MiddleName到FirstName MiddleName LastName进行排列。但是我的while循环正在跳过输入文件中的所有其他名称。

这是我的主要内容:

using namespace std;

int main() {

    string fullName;
    string lastName;
    string first_middleName;

    size_t pos;


    string fileName;
    ifstream inData;

    cout << "Please type the file name including extension(such as .txt)." << endl;
    cout << "If your file is in a different directory please specify the path:";

    getline(cin, fileName);
    inData.open(fileName.c_str());

    if(!inData) {
        cout << "Cannot open" << fileName << "." << endl;
        return 1;
    }

    getline(inData, fullName);

    while(getline(inData, fullName)) {
        pos = fullName.find(',');
        lastName = fullName.substr(0, pos);
        first_middleName = fullName.substr(pos + 2);
        cout << first_middleName << " " << lastName << endl;
        getline(inData, fullName);
    }


    inData.close();

    return 0;
}

最佳答案

这是因为每个循环读取两行

while(getline(inData,fullName)){
    ...
    getline(inData,fullName);
}

09-30 20:35