Mahmoud Mahmoud - 1 year ago 93
C Question

How to make while loop in c

Am trying to make while loop in my C code

like this:

char q ;
while( a == 'yes' )
/* my code */
printf("enter no to exit or yes to continue");

but when i input the char " q " .... the console is crashed

and stop working

what is my wrong in while loop ??

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download