I'm trying to read in a .csv file filled with floats. 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. 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. 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
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.