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
What happens
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 character . Accordingly, your while
loop checks for single characters but you give as an input a string .
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.