Is there a way to make this error checking any better? Or is there something I am forgetting? I am expecting an integer then string. I added the suggestions to the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
int main(void) {
// your code goes here
char line[150] = {0};
int sscanf_counter = 0;
int num = 0;
char string[150] = {0};
char dummy;
while(fgets(line, sizeof line, stdin))
{
printf("line is %s\n", line);
sscanf_counter = sscanf(line, "%d %s %c", &num, string, &dummy);
printf ("sscanf_counter: %d\n", sscanf_counter);
if (sscanf_counter == 2 && isalpha(string[0]))
{
printf ("Good value: %d\n", num);
printf ("string: <%s>\n", string);
}
else
{
printf ("BAD VALUE: %d \n", num);
printf ("string: <%s>\n", string);
}
memset(line, 0, sizeof line);
}
printf("Does this print? \n");
return 0;
}
I didn't want 222 to be converted to a string so I added a simple isalpha() check to my code. I want an actual number for my first value and actual alphabet characters not numbers converted to a string for the second value.
Output with small tweak:
aaa aaa
line is aaa aaa
sscanf_counter: 0
BAD VALUE: 0
string: <>
111 222
line is 111 222
sscanf_counter: 2
BAD VALUE: 111
string: <222>
111 aaa
line is 111 aaa
sscanf_counter: 2
Good value: 111
string: <aaa>
isalpha()check to my code.isalpha(string[0])is not defined for most negative values ofstring[0]. Highly portable code usesisalpha((unsigned char) string[0])