Before I leave the string section, I'd like to talk about two useful
functions that could come in handy later on. Both of these require the stdlib.h
header file.
First of all, atoi. This converts strings, like "23" or even "29dhjds" into integers (returning 23
and 29 respectively in this case).
atoi requires one char * argument and returns an int (not a float!).
If the string is empty, or first character isn't a number or a minus sign, then atoi returns 0.
If atoi encounters a non-number character, it returns the number formed up until that point.
|
#include <stdio.h>
#include <stdlib.h>
int main() {
char str1[] = "124z3yu87";
char str2[] = "-3.4";
char *str3 = "e24";
printf("str1: %d\n", atoi(str1));
printf("str2: %d\n", atoi(str2));
printf("str3: %d\n", atoi(str3));
return 0;
}
Output:
str1: 124
str2: -3
str3: 0
|