Javik
Javik

Reputation: 9

While loop won't stop despite fulflling condition

I want to insert a condition into my program using a while loop. At the end it will ask you if you want to repeat the program from the beginning. If you type in 'n' then the program stops, if you type in anything else you continue. The problem is even when you write in 'n' it still does continue. I'm giving the code so you can see it for yourself:

I'm not giving the rest of the program since it works fine, it's just the loop itself that's the problem. When I made a condition involving an integer it works fine, it's just when I want a char string there's a problem.

#include <stdio.h>
#include <stdbool.h>

int main()
{

  char cnd[1];

  while(cnd != 'n') {
    printf("Would you like to continue? If not, then type in 'n', if you do then type in anything else: ");
    scanf("%1s", &cnd);
  }
return 0;
}

Upvotes: 0

Views: 59

Answers (2)

Mostafa Ayaz
Mostafa Ayaz

Reputation: 478

The following code is safer without the need to define cnd as array like cnd[1] :

#include<stdio.h>
int main(){
char cnd;

while(cnd != 'n') {
    printf("Would you like to continue? If not, then type in 'n', if you do then type in anything else: ");
    scanf("%1s", &cnd);
}

return 0;
}

When running your code, the following error would encounter which is self-explanatory.

[Error] ISO C++ forbids comparison between pointer and integer [-fpermissive]

which refers to the error in while(cnd != 'n')

Upvotes: 0

Andra
Andra

Reputation: 1392

Why are you using char array?? You can just use a regular char

#include <stdio.h>

int main(){
    char cnd;
    while(cnd != 'n') {
        printf("Would you like to continue? If not, then type in 'n', if you do then type in anything else: ");
        scanf("%c", &cnd);
    }
    return 0;
}

Upvotes: 2

Related Questions