简体   繁体   中英

C: scanf doesn't work as I want

I want that the program controls the user's input (must be a char/letter), but if I put "xx" it goes out of the loop, why?

        char c;
        int i = 0;
        do{
            if(i!=0){
                printf("Wrong!\n");
            }
            printf("Insert char: ");
            scanf(" %c", &c);
            i++;
        }while(c<'a' && c>'z' && c<'A' && c>'Z');

-----> Edit/correct

This piece of code should read a single character from the keyboard (must be a letter, it does not matter whether it is lowercase or uppercase), if it were not so I write "wrong".

As you told me I corrected the condition of the do/while, now the code is:

            do{
                if(i!=0){
                    printf("Wrong!\n");
                }
                printf("Insert char: ");
                scanf(" %c", &c);
                i++;
            }while(!((c>='a' && c<='z') || (c>='A' && c<='Z')));

Input examples:

What I expect

  • 'a' -> exit to the loop
  • 'aa' -> remain in the loop
  • '.' -> remain in the loop
  • '..' -> remain in the loop

What happens

  • 'a' -> exit to the loop
  • 'aa' -> exit to the loop
  • '.' -> remain in the loop
  • '..' -> remain in the loop (but it print me two time "wrong")

If I do not put the space in the scanf, so ("%c"), the program prints me automatically "wrong" and "insert char" (it just makes a loop)

(ps I apologize if I had not explained very well the problem before)

Your condition for

while(c<'a' && c>'z' && c<'A' && c>'Z');

will never be true.

but if I put "xx" it goes out of the loop, why?

Since do-while is an exit-condition loop, the only time you enter the loop is the first time.

The specifier %c indicates a . Accordingly, your while loop checks for single characters but you give as an input a .

If you want to input a string , change your scanf statement to :

scanf("%s", &s);

as the specifier %c indicates a string . You will need to modify your while loop accordingly in order for your condition to become true at some point.

while(c<'a' && c>'z' && c<'A' && c>'Z')

is always false, that's why.

If it were true:

if(i!=0){ printf("Wrong!\n");}

will always print false(except the first time).

I don't know exactly what you want.

Your problem is in the condition, it's always false.

Example code:

#include <cstdio>
#include <cctype>

int main ()
{
    char c;
    do scanf("%c", &c);
    while(tolower(c)<'a' || tolower(c)>'z');
    printf("%c\n",c);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM