Converting string variable to float
I would like to convert a string variable to float.
When acquiring data from text file, I use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
while( getline( ifs, temp ))
{
numberOfFeatures++;
vecteur.clear();
string::size_type stTemp = temp.find(separateur);
number_descriptorEntries=0;
while((stTemp != string::npos)&&(number_descriptorEntries<6))
{
vecteur.push_back(temp.substr(0, stTemp-1));
temp = temp.substr(stTemp + 1);
stTemp = temp.find(separateur);
}
matrixe.push_back(vecteur);
}
return matrixe;
}
|
the matrix that I obtain is of type vector<Vec> where Vec is a vector of strings.
I want to convert each element of
matrixe to a float.
Thanks
Younes
i would use std::stringstream <sstream>
I used the following code. But at the runtime I obtain some incoherences in the retrieved data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
MatrixXd Vision::clustering(int i){
const int ROWS=63;
const int COLS=10;
const int BUFFSIZE=100;
MatrixXd array(ROWS,COLS);
//int **array;
char buff[BUFFSIZE];
ifstream ifs("Brisc_db.txt");
stringstream ss;
for(int row=0;row<ROWS-1;++row) {
ifs.getline(buff,BUFFSIZE);
ss<<buff;
for(int col=0;col<COLS-1;++col){
ss.getline(buff,5,',');
array(row,col)=atoi(buff);
// cout<<array(row,col)<<endl;
//**array=atoi(buff);
//(*array)++;
//cout<<array[row][col]<<" ";
ss<<"";
}
//array++;
ss.clear();
}
ifs.close();
return array;
}
|
There is a function for converting from string to float: see
std::stof:
1 2 3 4 5 6
|
// Example
std::string s1 = "1234.5678";
std::string s2 = "1.915e2";
std::string s3 = "-0.5e-5";
float f = std::stof(s1) + std::stof(s2) + std::stof(s3);
|
See
http://www.cplusplus.com/reference/string/stof/
Topic archived. No new replies allowed.