while循环跳过其他所有输入

时间:2013-02-08 19:57:06

标签: c++

我正在尝试编写一个程序,该程序将打开用户输入文件名,然后获取该文件中的名称,并将它们从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;
}

1 个答案:

答案 0 :(得分:5)

这是因为你每个循环读了两行

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