2016-10-02 180 views
0

相当简单的问题。下面是我的代码,我正在尝试阅读文本文件上每行的第一个单词。我对C++非常陌生,基本上不识字,所以生动的解释会非常有帮助。提前致谢!Getline在我的while循环中跳过第一行? (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次),状态,状态

+0

如果while循环内的条件非常有趣!怎么样cout << command << endl; – HazemGomaa

+0

将while(inFile >> readText)改为while(inFile >> command)并移除getline(inFile,command); inFile >>命令; – HazemGomaa

+0

哦...那么工作...谢谢!大声笑 – Yourchingoo

回答

0

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

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