我想我有一个初学者的问题。
我尝试逐行读取文件。
该文件位于/home/myhomedir 中,名为 text.txt 。 文件内容为
1
2
3
4
该文件具有访问权限,所有人都可以读写。
我想要:打开文件并逐行阅读。
所以我尝试了:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
try
{
ifstream myfile ;
myfile.open("/home/myhomedir/text.txt", ios::in);
if(myfile.is_open())
{
string line;
while (getline(myfile, line)) {
// do nothing, just get a line
// *
}
}
}
catch(int ex)
{
}
return 0;
}
已经到达*标记的地方(使用了netbeans的debug特性)。然而,这一行是空的,循环似乎只输入了一次。
就像打开一个空文件一样。
我做错了什么?
最佳答案
原因是,你不知道如何使用调试器。我修改了你的代码:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
try
{
ifstream myfile ;
myfile.open("/home/enedil/text.txt", ios::in);
if(myfile.is_open())
{
string line;
while (getline(myfile, line)) {
cout << line; // there's my modification
}
}
}
catch(int ex)
{
}
return 0;
}
输出是
1234
所以一切都是正确的。
关于c++ - 在 Linux 中使用 fstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23322614/