C++中文件流的输入输出

编写程序统计一个文件中的字符总数、非空白字符总数、字母总数和平均单词长度,并输出到屏     幕和输出文件output.txt。

要求:统计的文件为当前工程的main.cpp。输出文件要求和main.cpp在同一级目录,且程序中要求使用相对路径表示。Output.txt.

#include <iostream>

#include "co.h"

#include<codecvt>

#include<string>

#include<fstream>

using namespace std;



void coushow()

{

    string str, strone;

    ofstream  out;// 创建输出流对象

    out.open("Output.txt");// 建立文件关联,缺省为文本模式

    while (cin>>str>>strone)

    {

       out << str << ' ' << strone << ' '<<'\n';// 向流插入数据

    }

    out.close();// 关闭文件

}



void cinput()

{

    char  n[80] = { 0 };

    ifstream  ist("Output.txt");// 创建输入流对象并建立关联

    int letter = 0;//字母总数

    int notblank = 0;//非空白字符总数

    double word = 0;//单词个数

    int character = 0;//字符总数

    while (!ist.eof())

    {

       ist.getline(n, 80);

       cout << n << endl;//输出

       character += ist.gcount();//字符总数

       for (int i = 0; i < ist.gcount(); i++)//每一行都遍历

       {

           if (n[i] >= 'a' && n[i] <= 'z' || n[i] >= 'A' && n[i] <= 'Z')

           {

              letter++;

              if (n[i + 1] == ' ' || n[i + 1] >= '0' && n[i + 1] <= '9'|| n[i+1] =='\0')

              {

                  word++;

              }

           }

           if (n[i] != ' ' && n[i] != '\0') {

              notblank++;

           }

       }

    }

    cout << "字符总数:" << character << endl;

    cout << "字母总数:" << letter << endl;

    cout << "非空白字符总数:" << notblank << endl;

    cout << "平均单词长度:" << (letter / (word)) << endl;

}

int main(){

    /*写入文件流中*/

    coushow();

    /*读出text写入控制台的内容*/

    cinput();

}

 

输出效果:

 

在这里需要注意的是:int eof()cost 这个函数的用法遍历文件结束时,返回1,否则返回0;在这里进行了取反的处理。

猜你喜欢

转载自blog.csdn.net/qq_41979469/article/details/91356291