C ++一次读取一行时出了什么问题? [英] C++ What's wrong during reading a file one line at a time?

查看:104
本文介绍了C ++一次读取一行时出了什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const char *filename = "test.txt";
ifstream fin(filename);
char tmp[80];
while(!fin.eof()){
    int i = 0;
    fin.getline(tmp,80);
    while(tmp[i] != '\0'){
       std::cout << tmp[i];
       i++;
    }
    //if(fin.fail() && !fin.eof()){
      //  fin.clear();
        //if(fin.peek() == '\0')
          //   fin.get();
    //}
}


我不知道为什么输入istream停止.
我不知道为什么fin.getline(tmp,80)下次不能继续.
谢谢!


I don''t know why the input istream is stopped.
i don''t know why fin.getline(tmp,80) can''t go on at the next time.
Thank you!

推荐答案

您不会像下面那样将i 的值增加1(无限循环)

you are not incrementing the value of i by 1 as below(infinite loop)

const char *filename = "test.txt";
ifstream fin(filename);
char tmp[80];
while(!fin.eof()){
    int i = 0;
    fin.getline(tmp,80);
    while(tmp[i] != '\0')
    {
       std::cout << tmp[i];
       i++;
    }
    std::cout<<"\n";
    if(fin.fail() && !fin.eof()){
        fin.clear();
        if(fin.peek() == '\0')
             fin.get();
    }
}



还更改了代码以在文件中打印一行.



also changed the code to print one line as in the file


istream方法getline(char *,int)在读取最大数量的输入字符时会设置故障位标志.因此,我必须提供清除故障位标志的方法,然后它才能读取下一行.
谢谢那些给我建议的人.
The istream method getline(char *,int) would set failbit flag when it reads the maximum number of input characters. So,I must give the method to clear the failbit flag,then it can read next line.
Thank those who give me advice.


在所提到的代码中,您给出了初始化i = 0;即:始终引用该行中的第一个字符.这需要在循环内递增并进行检查.我认为这样就可以工作并打印整个文件.

In the mentioned code, you given the intialization i = 0; ie: always refer to the first character from the line. This needs to increment inside the loop and do the check. I think then it will work and print the whole file.

while(tmp[i] != '\0')
    {
       std::cout << tmp[i];
       i++;
    }


这篇关于C ++一次读取一行时出了什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆