24小时热门版块排行榜    

查看: 793  |  回复: 3
当前只显示满足指定条件的回帖,点击这里查看本话题的所有回帖

杨小云同学

新虫 (小有名气)

[求助] 利用c++处理csv文件的数据 已有2人参与

12.1,23,45
66,56,76.1
12.1,23.2,45,
如何用C++编一个程序读取csv文件里像上述的数据,求出每行的平均值呢?

发自小木虫IOS客户端
回复此楼

» 猜你喜欢

已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

never2338

木虫 (小有名气)

【答案】应助回帖

感谢参与,应助指数 +1
CODE:
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<string.h>
using namespace std;

int main(){
    ifstream fin("data.csv");//input file.
    ofstream fout("output.dat");//output file.
    string s;
    stringstream ss;
    char p[200];
    static long lines=1;

    while(fin!=NULL){
    int num=0;//data of float type in total in a line.
    float sum=0.0f;
    getline(fin,s,'\n');
    cout<<s<<endl;
    if(!fin)break;//end of file,break loop.
        if(fout.is_open()){
        fout<<lines<<":  ";//line number.
        }else{
            cout<<"File not found!"<<endl;
        }
    //split
    strcpy(p,s.c_str());
    char* token=strtok(p,",");
    while(token!=NULL){
        float a=0.0f;
        cout<<token<<endl;
        ss<<token;
        ss>>a;
        if(fout.is_open()){
        fout<<a<<",";
        }else{
            cout<<"File not found!"<<endl;
        }
        sum+=a;
        ss.clear();
        ss.str("");
        num++;
        token=strtok(NULL,",");
    }
    lines++;
        cout<<"Sum:"<<sum<<endl;
        cout<<"Average:"<<sum/num<<endl;
        fout<<"   "<<sum<<","<<sum/num<<endl;
    cout<<"============================"<<endl;

}
    fin.close();
    fout.close();
}

3楼2017-07-23 17:03:04
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
查看全部 4 个回答

杨小云同学

新虫 (小有名气)

最后一行最后一个逗号多打了,抱歉

发自小木虫IOS客户端
2楼2017-07-23 13:59:24
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

imyourkobe

铁杆木虫 (著名写手)

【答案】应助回帖


感谢参与,应助指数 +1
jjdg: 金币+1, 感谢参与 2017-07-24 22:22:10
就是读取文件,一行行读取,按逗号分隔,用数组存储或直接计算。
4楼2017-07-23 23:43:01
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
信息提示
请填处理意见