string conversion & file reading
Hi I'm a semi-beginner. I have a few questions about character arrays.
1. I have a number in scientific notation that I read in from a file, so the number is something like: 1.532E-017
I want to convert this number to a float. I know one way to do it is to parse the array into a base and an exponent portion and do some math:
float num = 100*hundreds+10*tens+1*ones*pow(10,exponent)
where hundreds, tens and ones would be placeholders for the respective digits in the base. But this seems too complicated. Is there any easier way?
2. Also each number that I read in has a paramter name. I'd like to store the numbers that I read from the file into a data structure with the corresponding parameter name: and I don't want to use a lookup table. Is there some way to do:
dataStructure.(param name read from file) = (param value read from file)?
Hope my questions aren't too long...
1)
or I believe:
2)
I'm not sure what you mean by a 'lookup table'...
some_file >> obj.member;
std::stringstream ss;ss << "1.532E-017";float some_num;ss >> some_num;
or I believe:
float some_num = boost::lexical_cast< float>( "1.532E-017" );
2)
I'm not sure what you mean by a 'lookup table'...
some_file >> obj.member;
Well if I read in the param name and value into a strings called sName and sValue respectively, to identify what I read I have to do something like:
if (!strcmp(sName, "param1")
{
dataStructure.param1 = sValue;
}
else if (!strcmp(sName, "param2")
{
dataStructure.param2 = sValue;
}
...
etc.
If I have 5000 different param names, not only do I have to have a data structure with 5000 fields, but I have to have 5000 if statements. I'm ok writing the data structure with 5000 fields (it's not that many actually), but I don't want to have to write 5000 if statements. What I really want to do is:
dataStructure.sName = sValue;
where sName and sValue are what I read from the file.
if (!strcmp(sName, "param1")
{
dataStructure.param1 = sValue;
}
else if (!strcmp(sName, "param2")
{
dataStructure.param2 = sValue;
}
...
etc.
If I have 5000 different param names, not only do I have to have a data structure with 5000 fields, but I have to have 5000 if statements. I'm ok writing the data structure with 5000 fields (it's not that many actually), but I don't want to have to write 5000 if statements. What I really want to do is:
dataStructure.sName = sValue;
where sName and sValue are what I read from the file.
std::map< std::string, std::string> param_value_map;...some_file >> str_name;some_file >> str_value;param_value_map[ str_name ] = str_value;...
Although it looks like you would prefer a C solution (considering you suggested strcmp()) instead of C++ (presented above). In that case, someone else can advise you.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement