Wrong value returns when the "coder-defined" anti_char() is used.

Hi,

I have coded a small code which only allows numbers (if i just wanted digits, i would use isdigit()) as inputs. I needed this because my program used to fail when i entered chars. That code should have made my job easier because it was supposed to ask for another entry when user enters a "non-integer" value.

This is interesting that if i use this code in "main" function, it just works. But when i change it into a function (like "anti_char") it doesnt work.

Code is here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
int anti_char(char[]);

int main()
{
    char t[4];
    printf("Value=");
    scanf("%c",&t);
    anti_char(t);
}

int anti_char(char input[])
{    
    char x[4];
    strcpy(x,input);
    re_value:
	int c; // c equals the integer version of x
    c = atoi(x); 
	char y[4];
	sprintf(y,"%d",c); //i printed c in the string y, allowing program to compare it with x
 	if(strcmp(x,y) == 0) // if x equals y
     {
	if (c >= 0 && c < 13)
    { // if c is between 0 and 13
    printf("True\n");
	return c; //i would like to return the integer to program, because it's going to be used in program.
    }
	else 
    {
    printf("Wrong value, please enter an integer between the specified interval.\nValue=");
    fflush(stdin);
    scanf("%c",&x);
    goto re_value;
    }
    }
	else
	{
	printf("Please enter an integer.\nValue=");
	fflush(stdin);
	scanf("%c",&x);
	goto re_value;
    }
}


Although i enter a value between the interval i specified, it says "please enter an integer"


Value=4
Please enter an integer.
Value=3
Please enter an integer.
Value=a4
Please enter an integer.
Value=2
Please enter an integer.
Value=14
Please enter an integer.
Value=5
Please enter an integer.
If that's C, it does not compile
16:2: error: a label can only be part of a statement and a declaration is not a statement.
That's a bad use of goto, by the way.


You've got several bad practices there, you should compile with warnings.
1
2
    char t[4];
    scanf("%c",&t);
"%c" will just read 1 character (at most `9'), it will not put a null terminator in the string.
And `&t' is not a pointer to a char.

Because you don't have a null terminator, the string comparison will fail (the copy is dangerous and unnecessary).
For error detection you could use strtol()


1
2
3
4
while( not std::cin>>value ){
   std::cin.clear();
   std::cin.ignore( std::numeric_limits<std::streamsize>::max() );
}
I have tried almost everything to solve this problem but not looking at the scanf part of the pre-function. The whole problem was %c.
I couldn't figure that out.

Thanks dude ;) it should work by now.

edit:and it didn't give any warnings.
edit2:i would like to write something without goto but i felt so lazy :P
Last edited on
Topic archived. No new replies allowed.