[英]C++ read in a CSV file as floats
I'm trying to read in a .csv file filled with floats. 我正在尝试读取一个充满浮点数的.csv文件。 I used this to build my code.
我用它来构建我的代码。 However, the data reads in correctly but is read in as a string but I want to use the data as floats.
但是,数据可以正确读取,但可以作为字符串读取,但是我想将数据用作浮点数。 If I try to use stof(string) I get an error that it is trying to convert a non number to a number.
如果我尝试使用stof(string),则会收到错误消息,它试图将非数字转换为数字。 So I went the really long way and converted the string to a char and that to a float, which works but is VERY ugly.
因此,我走了很长一段路,将字符串转换为char,然后将其转换为float,这很有效但是很丑陋。 However, once all the data is read in and is printed out with a cout the program my crashes
但是,一旦所有数据都被读取并打印出来,程序就会崩溃
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();
It seems I have stumbled upon the answer to my own question. 看来我偶然发现了我自己问题的答案。 Thanks to the above questions I started looking for different ways to convert the string to a float.
由于上述问题,我开始寻找将字符串转换为浮点数的不同方法。 The +2 in the print out can be ignored, was my "pinch" to make sure I wasn't dreaming
打印输出中的+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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.