qq_35996472
qq_35996472
2016-08-29 09:50

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条回答