`
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
// function prototypes
int get_key(int argc, char *argk[]);
int main(int argc, char *argv[]){
char *argv1 = argv[1];
get_key(argc, argv1);
return 0;
}
// function defination.
int get_key(int argc, char *argk){
// ensure single cmd line arg
if(argc < 2 || argc > 2){
printf("usage: ./caesar key(int) !\n");
return 1;
}
char str1[] = "2";
char str2[] = "23";
char str3[] = "a23";
char str4[] = "23b";
char str5[] = "a23b";
int len = strlen(str3);
int number;
for(int i = 0; i < len; i++){
if(isdigit(str3[i])){ // since isdigit() accept only char, not char*.
number = atoi(str3); // meaning if str3 did contain digits 0-9 from ascii chart.
}
}
return number;
}
`
hello guys, please i want to convert argv[1] to integer, without trusting the user. since isdigit() accept only char, not char*, thats why i am iterating through the str3 and atoi accepts char*. it works fine with str1 and str2. but for other string variables, it returns digits within them, for which cant be converted using atoi() or any other calculations. i want to report error messsage if any of argv[1] elements contains non digits 0-9 from ascii chart. thanks.
strol. It will populateendptrwhich you can use to tell whether the whole string is a number. man 3 strtol has examples.atoi(). It will always return a value that could have been a valid input.since isdigit() accept only char, not char*. If you want to do it that way then check the whole string first before callingatoi. Otherwise usestrtolas suggested already.'strtolcan definetely be used to do the case you need. So you need to read the manual, understand the paramters and modify the example to do the extra checks to determine whether the string contains any non-digit characters.