tags:

views:

66

answers:

3

I want to know how to type cast a string into integer , and not use sprintf() in C

+3  A: 

There's no such thing as a string data type in C. But to your question, you can use int atoi ( const char * str ) and remember to include <stdlib.h>

Khnle
Keep in mind that atoi is pretty new in the C-world, C90 and C99. If you don't have sprintf for some reason, you're unlikely to atoi.
D'Nabre
@D'Nabre: `atoi` is _new_???
James McNellis
+1  A: 

You can't cast a char array/const char * into an integer in C, at least not in a way that gives you a sensible integer result[1]. The only exception is if you use it to convert a single char into an integer, which is basically just widening it if you look at the bit representation.

The only way you can do the proper conversion functions like atoi or sscanf.

[1] Yes, I know you can convert a pointer (const char *) into an integer, but that converts the value of the pointer and not the value of the data it points to.

Timo Geusch
You meant sscanf I think, not fscanf.
progrmr
I did, thanks for pointing this out.
Timo Geusch
A: 

C doesn't have strings but it does have char arrays (which we often call strings), such as:

char someChars[] = "12345";

You can convert (not the same as type cast) the contents of the character array to an int like this:

int result;
sscanf(someChars, "%d", &result);

Or using atoi:

int result = atoi( someChars );

Type casting is like taking a bottle of Coke and putting a Pepsi label on the bottle.
Type conversion is like pouring a bottle of Coke into an Pepsi can. Maybe it will fit.

progrmr