-
Using isalpha()
I have tried & tried & tried to figure out what's wrong with my code but I can't . I's supposed to give an error if the user enters anything else but an integer . So something like : 34j , should be comming up as an error.
Thanks for any help you can give ! :)
Code:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXLINE 25
int check(char *line);
char line[MAXLINE];
int error,n,digit,flag;
int i = 0;
int flag = 0;
void main(){
do{
printf("Input a posetive integer: ");
if (fgets(line,MAXLINE,stdin) != NULL){
digit = check(&line);
error = ((sscanf(line,"/t%d/t",&n) != 1 || n <= 0) && (digit == 1));
}
if (error)
printf("\nERROR: Do it again .\n");
else
printf("There was no error!");
}while (error);
}
int check(char *line){
while((i < MAXLINE) && (flag == 0)){
if (isalpha((int)line[i]))
flag = 1;
++i;
}
if (flag = 0)
return 0;
else
return 1;
}
-
Common problem, a swap of the assignment and the testing operator...
Code:
if (flag = 0)
return 0;
else
return 1;
notice you're assigning flag to 0, not testing if it EQUALS zero :D
Simple mistake that we all make every now and then, just change the = to a == and you'll be set to go
-
Thanks! Ive done that , but while debugging after i've entered the values 5t , t5, t, 5
the 5 still gives an error while it shouldn't ??
-
You're using a lot of global variables in this program that are causing you more of a headache then anything, heh.
What's happening is
1) not resetting the i to 0
2) not resetting the flag to 0
3) you should only test (i < strlen(line)) in order to only test the inputted data.
Code:
int check(char *line){
i=0;
flag=0;
while((i < strlen(line)) && (flag == 0))
{
if (isalpha((int)line[i]))
flag = 1;
++i;
}
if (flag == 0)
return 0;
else
return 1;
}
-
Thank you soooo much it works now, it was such a pain in the butt this program lol . Thanks again! :)