天天看點

c++讀取txt,并将其中的實數顯示并統計其總個數和平均值,考慮空行(檔案讀取,字元串轉換數字,字元轉換字元串)

#include <iostream>
#include <sstream>
#include <cassert>
#include <cstring>
#include <fstream>
using namespace std;

int main()
{
    ifstream read;
    string file="E:\\test.txt";//檔案路徑
    read.open(file.data());
    assert(read.is_open());//如果打開檔案失敗,則輸出錯誤消息,并終止運作
    read >> noskipws;//設定可以讀取空白符
    string str1,str2;
    char c;
    int cou=0;//計數
    double sum=0, temp;
    while(!read.eof())
    {
        read >> c;
        if(c ==' '||c=='\n'||read.eof())
        {
            //字元串轉換為數字
            stringstream s;
            s.str(str1);
            s >> temp;
            //求和
            sum+=temp;
            //設為0,防止檔案末尾出現空行
            temp = 0;
            str1="";
        }
        else
        {
            cou++;//統計數字個數
            //将字元轉換為字元串
            stringstream ss;
            ss << c;
            str2=ss.str();
            str1+=str2;
        }
    }
    cout<<"實數個數為:";
    cout<<cou<<endl;
    cout<<"平均值為:";
    cout<<sum/cou<<endl;
    
    read.close();
}
           

繼續閱讀