第十四周项目1 - 小玩文件(1)

本文介绍了一个使用 C++ 编写的简单程序,该程序能够读取名为 abc.txt 的文本文件,并统计文件中所有字符的数量。通过 fstream 类的 get 方法逐个读取字符并计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)下面程序的功能是统计文本文件abc.txt中的字符个数,请填空将程序补充完整。

  1. #include <iostream>  
  2. #include <cstdlib>  
  3. #include _____________ // (1)  
  4. using namespace std;  
  5. int main()  
  6. {  
  7.     fstream file;  
  8.     file.open("abc.txt", _________); // (2)  
  9.     if(!file) {  
  10.         cout<<"abc.txt can’t open."<<endl;  
  11.         exit(1);  
  12.     }  
  13.     char ch;  
  14.     int i=0;  
  15.     while( _____________) // (3)  
  16.     {  
  17.         file.get(ch);  
  18.          _____________; // (4)  
  19.     }  
  20.     cout<<"Character: "<<i<<endl;  
  21.     file._____________;// (5)  
  22.     return 0;  
  23. }  
填充如下:

#include <iostream>
#include <cstdlib>
#include <fstream>// (1)
using namespace std;
int main()
{
    fstream file;
    file.open("abc.txt",ios::out); // (2)
    if(!file)
    {
        cout<<"abc.txt can’t open."<<endl;
        exit(1);
    }
    char ch;
    int i=0;
    while(!file.eof()) // (3)
    {
        file.get(ch);
        ++i; // (4)
    }
    cout<<"Character: "<<i<<endl;
    file.close();// (5)
    return 0;
}
心得:

其实有个纠结的地方。。。刚开始要打开文件时是要ios::out还是ios::in啊?都试了试完全没区别啊
图片:


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值