-3

I have a code below that asks if the user wants to retry or not. If the user enters no, the program will terminate. My code doesn't work and the loop still runs even if the input is "no"

#include<stdio.h>
int main()
{
    char x[5];        
    do
    {
        printf("would you like to try again?");
        scanf("%s",&x);
    }
    while(x != "no");

getch(); return 0; 
}

I've tried adding a space in the scanf just like for characters to consume the newline but it also doesn't work. sorry for a very noob question.

Obito
  • 77
  • 12

5 Answers5

1

You should use strcmp() to compare strings.

do { ... } while (strcmp(x, "no") != 0);
timrau
  • 22,578
  • 4
  • 51
  • 64
1

The issue of comparing an char array has been addressed by other answers and comments. There is another possible problem with an array of 5 elements being overrun by an input of "Yes, I would like to try again." Using %4s will limit scanf. Another option would be to use fgets ( x, sizeof ( x), stdin); fgets will include the newline so the comparison would be to "no\n" instead of "no".

#include<stdio.h>
#include<string.h>
int main()
{
    char x[5];
    do
    {
        printf("would you like to try again?");
        scanf("%4s",x); // %4s prevent overrun. x is array, no need for &   
    }                              
    while( strcmp ( x, "no") != 0);

    getchar();            
    return 0;             
}     
user3121023
  • 8,181
  • 5
  • 18
  • 16
0

You can't compare two strings by using !=, since the value of x is actually the memory address of your string.

You must include string.h and use the strcmp() function. (Take a look at the doc.)

Richard-Degenne
  • 2,892
  • 2
  • 26
  • 43
0

x is just stand for the base address of the array while "no" is just stand for the address of the literal string [no\0]. So x != "no" is comparing two addresses which is always false.

You should use strcmp in the standard C lib.

Grissiom
  • 11,355
  • 3
  • 18
  • 23
0

Your problem is at the condition of the while loop. x is an array that contains characters. Using the x!="no" you are checking the base address of the array (to be more specific when you drop the brackets the compiler translate that as a pointer that points at the array x at the cell x[0,0]).

So the best solution and the easiest one to your problem is to use the strcmp function. The strcmp stands for string compare. This function compares character by character between two strings using the ascii code. The strcmp function returns zero only if the two strings are the same.So at your case you should use something like:

while(strcmp(x,"no")!=0){
....
Spikatrix
  • 20,225
  • 7
  • 37
  • 83