Am trying to make while loop in my C code
like this:
main()
{
char q ;
while( a == 'yes' )
{
/* my code */
printf("enter no to exit or yes to continue");
scanf("%s",q);
}
}
but when i input the char " q " .... the console is crashed
and stop working
what is my wrong in while loop ??
You can't compare a string with a == 'yes'. You need to use strcmp function.
You need something like this:
int main(int argc, char **argv)
{
char a[200];
strcpy(a, "yes");
while( !strcmp(a, "yes") )
{
/* my code */
printf("enter no to exit or yes to continue");
scanf("%s",a);
}
}
There are several errors:
"yes", not 'yes'.scanf expects an address of the variable: scanf("%s", &q), not scanf("%s", q).char q[4]), not character one (char q).a referenced in condition while( a == 'yes') isn't declared.'\n' is printed.So what you probably need is:
#include <stdio.h>
#include <string.h>
#define INP_SIZE 3
int main() {
char inp[INP_SIZE + 1] = { 0 };
while (strcmp(inp, "yes")) {
printf("enter yes to continue or whatever else to exit\n");
scanf("%3s", inp);
}
return 0;
}
P.S. I thought about constructing a format string to avoid duplication of 3, but my laziness won.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With