我正在尝试读取给定文件的所有行.
由于某种原因,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;
}
Run Code Online (Sandbox Code Playgroud)
../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]
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我想知道它进入循环的次数,变量i.输出是:
solid,Tree,4,4,[20 20]
1
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
您的文件有CR换行符而不是LFUnix样式操作系统的标准,因此getline()将整个文件作为单行读取.您可以使用以下命令修复该文件Terminal:
tr '\r' '\n' < init.txt > newinit.txt
mv newinit.txt < init.txt
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |