C ++以浮点数的形式读取CSV文件

时间:2019-01-09 19:37:47

标签: c++ string csv

我正在尝试读取一个填充有浮点数的.csv文件。我使用this来构建代码。但是,数据可以正确读取,但可以作为字符串读取,但是我想将数据用作浮点数。如果我尝试使用stof(string),则会收到错误消息,它试图将非数字转换为数字。因此,我走了很长一段路,将字符串转换为char,然后将其转换为float,这很有效但是很丑陋。但是,一旦所有数据都被读取并打印出来,程序就会崩溃

trackBarFile.open("test2.csv");


std::string line, line2, line3;
int count;
std::string token;
float tokenNum,lineFloat,line2Float,line3Float;
char cstr[5],cstr2[5];

while (getline(trackBarFile, line,',')) 
{

    cstr[line.size()+1];
    strcpy(cstr, line.c_str());
    lineFloat = atof(cstr);

    getline(trackBarFile, line2,',');
    cstr[line2.size()+1];
    strcpy(cstr, line2.c_str());
    line2Float = atof(cstr);

    getline(trackBarFile, line3);       
    cstr2[line3.size()+1];
    strcpy(cstr2, line3.c_str());
    line3Float = atof(cstr2);


    std::cout<<line<<","<<lineFloat<<"   , "<<line2<<","<<line2Float<<"  ,  "<<line3<<","<<line3Float<<std::endl;


}

trackBarFile.close();

1 个答案:

答案 0 :(得分:1)

似乎我偶然发现了自己问题的答案。由于上述问题,我开始寻找将字符串转换为浮点数的不同方法。打印输出中的+2可以忽略,这是我的“捏”,以确保我没有做梦

trackBarFile.open("TrackBarSignal.csv");

std::ofstream fout;
fout.open("Output_ReadInCSV.txt");

std::string line, line2, line3;
int count;
float tokenNum,lineFloat,line2Float,line3Float;

while (getline(trackBarFile, line,',')&&getline(trackBarFile, line2,',')&&getline(trackBarFile, line3)) 
{

    lineFloat = (float)atof(line.c_str());
    line2Float = (float)atof(line2.c_str());
    line3Float = (float)atof(line3.c_str());

    std::cout<<line<<","<<lineFloat+2<<"   ,   "<<line2<<","<<line2Float+2<<"  ,  "<<line3<<","<<line3Float+2<<std::endl;

}

trackBarFile.close();