qq_35996472 2016-08-29 09:50 采纳率: 0%
浏览 1199

C++文件的输入和输出问题

先创建一个文本

     ofstream savefile("savefile.txt");
    savefile << "hello world";
    savefile.close();

然后

  ifstream openfile("savefile.txt");
    int i = 0;
    char ch;
    while (i < 30)
    {
        ch = openfile.get();
        cout << ch;
        ++i;
    }

结果正常

 hello world
Process returned 0 (0x0)   execution time : 0.348 s
Press any key to continue.

修改一句代码后

 ifstream openfile("savefile.txt");
    int i = 0;
    char ch;
    while (i < 30)
    {
        openfile.get(ch); //★
        cout << ch;
        ++i;
    }

结果变成

 hello worldddddddddddddddddddd
Process returned 0 (0x0)   execution time : 0.495 s
Press any key to continue.


原来的代码是

 ifstream openfile("savefile.txt");
    char ch;
    while (!openfile.eof())
    {
        openfile.get(ch);
        cout << ch;
    }

输出结果最后一个字符复制了一遍,经查阅说eof()读到最后一个字符会多读一次,因此末尾字符输出两次

 hello worldd
Process returned 0 (0x0)   execution time : 0.606 s
Press any key to continue.

经过修改

 ifstream openfile("savefile.txt");
    char ch;
    while (!openfile.eof())
    {
       ch = openfile.get(); //★
        cout << ch;
    }

结果正常了

 hello world
Process returned 0 (0x0)

于是有了上面的代码将问题放大来分析,
这里的ch = openfile.get();和openfile.get(ch);有何不同?新手求指点谢谢

  • 写回答

2条回答

  • AlbertS 博客专家认证 2016-08-29 10:05
    关注

    就是不同的重载吧,如果按你的运行结果来看是,到了文件结尾openfile.get(ch);这种写法不会把ch覆盖而已,所以还保存的字母d,而ch = openfile.get();返回的是不可见字符吧,我感觉你应该把最后这个字符装成数字看一下

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器