我试图读取给定文件的所有行。
出于某种原因,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
为什么会这样?
答案 0 :(得分:6)
您的文件有 CR 换行符而不是 LF ,这是Unix风格的操作系统的标准,因此Traceback (most recent call last):
File "C:-----------------------------.py", line 17, in <module>
numguesses = numguesses() + 1
将整个文件作为一行读取。您可以使用以下代码修复getline()
中的文件
Terminal