• Advertisement
Sign in to follow this  

string conversion & file reading

This topic is 4652 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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...

Share this post


Link to post
Share on other sites
Advertisement
1)

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;

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement