Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make while loop in c

Tags:

c

while-loop

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 ??

like image 722
Mahmoud Avatar asked Nov 21 '25 17:11

Mahmoud


2 Answers

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);
    } 
}
like image 74
Pablo Santa Cruz Avatar answered Nov 23 '25 07:11

Pablo Santa Cruz


There are several errors:

  1. String literals should be surrounded by double quotes: "yes", not 'yes'.
  2. String literals can't be compared to character variables.
  3. scanf expects an address of the variable: scanf("%s", &q), not scanf("%s", q).
  4. Apparently, you need array variable (char q[4]), not character one (char q).
  5. Variable a referenced in condition while( a == 'yes') isn't declared.
  6. You won't get your message on the screen since it's being buffered until '\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.

like image 32
Alex Bakulin Avatar answered Nov 23 '25 08:11

Alex Bakulin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!