Concerns about '\0' and '\n' inside a loop
Good afternoon fellas.
I'm concerned about the usage of a function I wrote to discover if a string is a number in addition with atoi. I thought I could do this:
Code:
/* if it reached the null terminator, then all the chars where numbers. */
int isanumber(char* s) {
int i;
for(i = 0; isdigit(s[i]) && s[i] != '\0'; i++)
;
if(s[i] == '\0')
return 1;
return 0;
}
instead of, the only thing that worked was:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#ifndef MAXSIZE
#define MAXSIZE 100
#endif
int Atoi(char s[]);
int isanumber(char* s);
int Atoi(char s[])
{
int i, n, sign;
for(i = 0; isspace(s[i]); i++)
;
sign = (s[i] == '-') ? -1 : 1;
if(s[i] == '+' || s[i] == '-')
i++;
for(n = 0; isdigit(s[i]); i++)
n = 10 * n + (s[i] - '0');
return sign * n;
}
/* if it reached the line feed, then all the chars where numbers. */
int isanumber(char* s) {
int i;
for(i = 0; isdigit(s[i]) && s[i] != '\n'; i++)
;
if(s[i] == '\n')
return 1;
return 0;
}
int main(void)
{
char* strnum = malloc(MAXSIZE * sizeof(char));
int num;
do {
printf("Enter a number: ");
if(fgets(strnum, MAXSIZE, stdin))
num = Atoi(strnum);
} while(!(isanumber(strnum)));
printf("You entered: %d\n", num);
free(strnum);
return 0;
}
how's that?