|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
|||
|
|||
|
String to integer
I'm coding a windows application, and I need to read a string and convert it to an integer.
Currently, I'm currently using _ttoi, which works as expected for a raw decimal integer. Now, what if I want to be able to use hex codes and such? Is there a function that can take a string like '0x32' and return the number 50? Coding it by hand would be easy, I just figure there's got to be some kind of pre-written one out there. |
|
#2
|
||||
|
||||
|
Hehe, I was about to code a similar function just now for my own project, when suddenly I remembered a function from a long time ago.
It's called sscanf(). It works the same as scanf() except that it uses a string for its first argument and a format string for the second argument (sort of like sprintf()). If you want, here's some code I tried out:Code:
#include <stdio.h>
int main() {
char *foo = "F00";
int x;
sscanf(foo, "%X", &x);
printf("Hex %s is dec %d", foo, x);
return 0;
}
Hope this helps! |
|
#3
|
|||
|
|||
|
Beautiful. Using a %i formatting string does exactly what I wanted it to do: the user can enter either decimal or hexidecimal and the function will sort it out accordingly.
Thanks! |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > String to integer |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|