zoukankan      html  css  js  c++  java
  • c++读取文本文件

    首选创建一个包含数字的文本文件。该文件命名1.txt

    c++程序实现如下:

    #include<iostream>
    #include<fstream>//文件I/O支持
    #include<cstdlib>//提供exit()
    const int SIZE = 60;//限制变量
    int main()
    {
    	using namespace std;
    	char filename[SIZE];
    	ifstream inFile;//对象输入
    	cout << "enter name of data file";
    	cin.getline(filename, SIZE);
    	inFile.open(filename);//关联文件
    	if (!inFile.good())//是否打开文件
    	{
    	    cout << "could not open the file" << filename << endl;
    		cout << "program terminating.
    ";
    		exit(EXIT_FAILURE);
    
    		}
    		double value;
    		double sum = 0.0;
    		int count = 0;//读入的数
    		inFile >> value;//取第一个值
    		while (inFile.good())
    
    		{
    			++count;
    		   sum += value;
    		   inFile >> value;
    
    		}
    		if (inFile.eof())
    			cout << "end of flie reached.
    ";
    		else if (inFile.fail())
    			cout << "input .
    ";
    		else
    			cout << "input .
    ";
    		if (count == 0)
    			cout << "no data processed.
    ";
    		else 
    		{
    			cout << "item ream:" << count << endl;
    			cout << "sum: " << sum << endl;
    			cout << "average" << sum / count << endl;
    
    		}
    		inFile.close();
    		system("pause");
    		return 0;
    		
    }
    

      

    运行结果:

  • 相关阅读:
    20171012
    BZOJ[2563] 阿狸和桃子的游戏
    BZOJ[1028] [JSOI2007]麻将
    BZOJ[1972] [Sdoi2010]猪国杀
    BZOJ[1033] [ZJOI2008] 杀蚂蚁antbuster
    P5651 基础最短路练习题
    P3047 [USACO12FEB]Nearby Cows G
    P6190 魔法
    P2391 白雪皑皑 / BZOJ 2054 疯狂的馒头
    CSP 2020 J/S 初赛游记
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/9786334.html
Copyright © 2011-2022 走看看