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

      

    运行结果:

  • 相关阅读:
    函数及其表示
    集合等离散数学内容
    求和
    分式·新方法
    弹力、重力、摩擦力
    洛谷 P1357 花园
    浮力
    因式分解·新方法
    压强
    洛谷 P2051 [AHOI2009]中国象棋
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/9786334.html
Copyright © 2011-2022 走看看