Can it be done? Can i convert a char * to a variable?
The reason is that i have a function that extracts 2 numbers out of a string (separated by a ",") using strtok, and puts them into separate variables. eg. 1,2 to a=1 b=2.
Is there an easier way to do this? please help.
you can convert a char to a number rather easily. Assuming you are using ASCII encoding, you need to know the characters ascii value, and the ascii value of what you want to convert it to, then with some rather simple math you can have your character converted to a number!!!
Once you understand the algorithm it is then applicable to all 'integers'. If you want a decimal number there will be a few extra steps, but can still be done.
Wow, 13 lines and a comment "this is not a complete program". Ya, really stupid. sstream does not do what it was meant to do (format strings). The stream mechanism is unintuitive and super verbose, and stores the format as code instead of data, making internationalization a huge nightmare.
Actually, I misread the article, I doesn't even do what the OP wants. He wants to separate two numbers with a comma between them, not get a float with a comma in it.
The article doesn't show any possible thing you can do with stringstreams, it just shows how to convert strings to numbers.
If the to get two numbers separated from a comma the code would be the following:
1 2 3 4
istringstream ss ( "123,456" );
double a,b;
char c; // used to remove the comma and spaces around it
ss >> a >> c >> b;
You can use ignore instead of reading a character to skip the comma.
Ya, that extracts the numbers, but *scanf also validates the format. In the event that the string does not match the format, sscanf will return 1 or 0 early, instead of returning 2, the number of arguments. This service is essential for input from humans, who make typos all the time. The fact that input, validation, and assignment are all done at once is a better interface than one relying on the user to write the same test over and over. In fact, it makes it easy to write things which for example match commands for a program:
1 2 3 4 5 6 7
if(sscanf(line,"load %100s",name)>0){
//load the file.
}elseif(sscanf(line,"print %n",i)>0){
//print data for pokemon no. i.
}elseif(sscanf(line,"print %100[a-zA-Z ]",name)>0)
//print data for pokemon named.
}