无法从文件中读取,奇怪的行为

Cannot read from a file, weird behavior

我正在尝试读取给定文件的所有行。
出于某种原因,std::getline 没有按预期工作。
main.cpp:

#include <iostream>
#include <fstream>
#include <string>
int main() {
    std::string filePath = "../init.txt";
    std::ifstream inputFile(filePath);
    std::string str;
    int i = 0;
    while (std::getline(inputFile,str)) {
        std::cout << str << std::endl;
        i++;
    }
    std::cout << i << std::endl;
    inputFile.close();
    return 0;
}

../init.txt:

Game
battlefieldSize,100,200
players,2
soldiers,3
p1,human
normal,[2 3],M16
paramedic,[10 31]
sniper,[5 12],UZI
p2,computer,0
normal,[90 112],Missile
sniper,[90 113],M16
normal,[65 100],M16
Objects
weapon,M16,[5 5]
Armor,BodyArmor,0.8,[1 2]
weapon,Missile,[15 115]
solid,Tree,4,4,[20 20]

如您所见,我想知道它进入循环的次数,变量为 i。输出为:

solid,Tree,4,4,[20 20]
1

为什么会这样?

你的文件有 CR 换行符而不是 Unix 风格操作系统的标准 LF,所以 getline() 是将整个文件作为一行读取。您可以使用以下方法修复 Terminal 中的文件:

tr '\r' '\n' < init.txt > newinit.txt
mv newinit.txt < init.txt