Getline跳过while循环中的第一行??(c++)

Getline skips the first line in my while loop?? (C++)

本文关键字:一行 c++ while 跳过 循环 Getline      更新时间:2023-10-16

相当简单的问题。下面是我的代码,我试图读取文本文件中每行的第一个单词。我对c++还是个新手,基本上是文盲,所以一个生动的解释会很有帮助。提前感谢!

我想要的输出是:

战士(5次),状态,战斗(5次),状态(当然分开行)

但是我得到的是:

战士(4次),状态,战斗(5次),状态

下面是我的代码:
int main() {
    string readText;
    string command;
    string firstName;
    string skip;
    int strength;
    ifstream inFile("warriors.txt");
    if (!inFile) {
        cout << "File will not open" << endl;
    }
    else {
        while (inFile >> readText) {
            getline(inFile, command);
            inFile >> command;
            if (command == "Warrior") {
                cout << "warrior" << endl;
            }
            else if (command == "Battle") {
                cout << "battle" << endl;
            }
            else if (command == "Status") {
                cout << "status" << endl;
            }
        }
    }
}
另一个问题,为什么当我改变
    while(inFile >> readText)

    while(inFile)

我现在的输出是:战士(4次),状态,战斗(5次),状态,状态

通过使用(inFile>>)和getline()在一个循环中读取多行。你的while循环应该看起来像

while (inFile >> command){
  cout << command << endl;  
}