parse_string_to_int
| parse_string_to_int | |
|---|---|
| Turn-in directory | 05_parse_string_to_int/ |
| Files to turn in | parse_string_to_int.c |
| Allowed functions | none |
- Write a function which parses a string
strinto an integer, and returns the value. - The string should contain a valid decimal integer. If it doesn't, your function should return
0. - The string can start with 1
'-'character, in which case your function should return a negative number. - If you encounter any character that is not a digit, or a
'-'at the start, your function should return0. - Don't worry about the number in the string being to large to fit inside an integer. We will consider this undefined behaviour, meaning your code can do whatever you want in this case, as long as it doesn't crash.
include <stdio.h>
int parse_string_to_int(char* str);
int main(int argc, char **argv)
{
if (argc < 2) {
return 1;
}
char *str_from_parameters = argv[1];
int num = parse_string_to_int(str_from_parameters);
printf("%d\n", num);
return 0;
}
Example output:
$ ./a.out "-5000"
-5000
$ ./a.out "0039"
39
$ ./a.out "--45"
0
$ ./a.out "764.34"
0