I want to know how to type cast a string into integer , and not use sprint开发者_运维问答f() in C
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>
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.
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.
精彩评论