Reputation: 1
My problem is when i input more than 1 number or characters(ex:156) the value 56 directly go to my next function ( f1, f2 ). How can i prevent that and print out that is an error ? (p.s : i'm new so if you guys can help me w/o using iostream, it'd be great
char c;
printf("menu");
printf("Please enter the option 1 - 4, press q to quit\n");
input_c:
scanf("%c",&c);
do{
switch (c)
case '1': f1();
break;
case '2': f2();
break;
case 'q': quit();
break;
default: goto input_c;
break;
}
i edited this as my original code which lead me to the same problem
Upvotes: 0
Views: 83
Reputation: 12658
In char c[2];
declaration, c
is a array of 2 characters ranging from index 0 to 1. So while reading the input into it, scanf("%c", &c[i])
should be used.
You cannot use array index as 2 in statement switch (c[2])
, since array indexing starts from 0
in C
.
main() {
char c;
scanf("%c", &c);
switch(c) {
case '1': f1(); break;
case '2': f2(); break;
case 'q': quit(); break;
default: //blah
}
The above method can be employed with simplicity.
Upvotes: 1
Reputation: 56479
You're reading a character so, strlen
on it is not correct and will make undefined behavior. Second, your array size is 2, so you can index it by 0 and 1. c[2]
can invoke undefined behavior again.
Just use a simple character variable instead and replace goto
by while
:
char c;
while(true)
{
scanf("%c",&c); // cin >> c;
switch (c)
{
case '1':
f1();
break;
case '2':
f2();
break;
case 'q':
quit();
break;
}
}
Upvotes: 0
Reputation: 1476
The reason of this behavior is because you declared an array of chars [2] and you're only using one of its elements (first). So when you input 145, it takes the 1 only and that's why it goes to the first function.
Upvotes: 0