Reputation: 127
I'm trying to write a method to set 2 variables to the numbers in a char string. The string would look something like:
[-][1][ ][ ][ ][ ][2][.][0][4]
Where the numbers -1 and 2.04 could be extracted. I know the method signature could look something like this:
sscanf(array[i],"%d%f",&someint,&somedouble)
But I'm honestly not sure how to go about writing it. Any help would be greatly appreciated
Upvotes: 0
Views: 448
Reputation: 3172
If the input is provided by user, e.g. someone has typed it, first you should normalize it: change many spaces to one, replace tabs with space, replace comma with point (some folks use comma for decimal separator instead of point), cut leading and trailing spaces, etc. Let's make sscanf()'s (or whatever you choose for parsing) job easier.
Upvotes: 0
Reputation: 775
This should do your job:
int x;
float y;
const char* ss = "-1 2.04";
istringstream iss(ss);
iss >> x >> y;
Upvotes: 3
Reputation: 5114
you're almost there :
sscanf(array[i], "%d %lf",&someint, &somedouble)
where the space means "0, 1 or more of any blank character"
but if you are using C++ and not C, better start off with the C++ streams. It will be much easier.
#include <sstream>
std::istringstream my_number_stream(array[i]);
if (!(my_number_stream >> std::skipws >> someint >> somedouble)) {
// oh noes ! an error !
}
Upvotes: 4