• 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;
    		
    }
    

      

    运行结果:

  • 相关阅读:
    python3 flask 文件下载服务器
    jquery cdn加速
    cherry 与sqlite
    cherry 与react.js
    cherrypy json 解析
    cherrypy cookies
    cherrypy 打印日志
    cherrypy pytest 覆盖,测试代码
    cherrypy ajax 请求
    cherrypy 访问css文件
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/9786334.html
Copyright © 2020-2023  润新知