Samuel
Samuel

Reputation: 405

Comparing string input with another string

I have a simple program but I am missing something because when it compares the inputted string, it always does not equal 0.

My code:

#include <stdio.h>
#include <string.h>

int main()
{
int loop = 1;
char response[9];
char *Response;

printf("Enter a string: ");

while(loop = 1)
    {
    scanf("%s", &response);
    Response = response;

    if(strcmp(Response,"Random") != 0 || strcmp(Response,"Database") != 0 || strcmp    (Response,"Both") != 0)
        printf("\n\"%s\" is an invalid entry. Valid responses are: \"Random\", \"Database\", or \"Both\": ", Response);

    else
        break;
    }

printf("\nYour string is: %s\n", Response);

return 0;
}

When I enter "Random", "Database", or "Both", it still thinks the string is invalid. Please help. Thanks!

Upvotes: 0

Views: 79

Answers (4)

Barmar
Barmar

Reputation: 782489

If the user enters Random, then you get:

  • strcmp(Response, "Random") != 0 => 0
  • strcmp(Response, "Database") != 0 => 1
  • strcmp(Response, "Both") != 0 => 1

Since (0 || 1 || 1) => 1, your if succeeds and the error message is printed.

You need to connect the comparisons with and, not or.

if(strcmp(Response,"Random") != 0 && strcmp(Response,"Database") != 0 && strcmp(Response,"Both") != 0)

Then (0 && 1 && 1) => 0, and the if doesn't print the error message.

Upvotes: 2

Rogalla Fabian
Rogalla Fabian

Reputation: 23

Use strncmp:

if (strncmp(str, "test", 4) == 0) { printf("it matches!"); }

Use this link to more about this

http://www.cplusplus.com/reference/cstring/strncmp/

Upvotes: -1

Jonathan Leffler
Jonathan Leffler

Reputation: 755006

You are testing whether the string is not 'Random', or not 'Database', or not 'Both'.

Suppose it is 'Random': it surely isn't 'Database', so you report that it is not valid.

Replace || with &&.

Upvotes: 2

sukhvir
sukhvir

Reputation: 5575

change to this:

#include <stdio.h>
#include <string.h>

int main()
{
    int loop = 1;
    char response[9];
    char *Response;

    printf("Enter a string: ");

    while(loop = 1)
        {
        scanf("%s", &response);
        Response = response;

        if(strcmp(Response,"Random") == 0 || strcmp(Response,"Database") ==0  || strcmp    (Response,"Both") ==0 ){
        //correct response
            break;
        }else{
            printf("\n\"%s\" is an invalid entry. Valid responses are: \"Random\", \"Database\", or \"Both\": ", Response);
        }

    }

    printf("\nYour string is: %s\n", Response);

    return 0;
}

Output

Sukhvir@Sukhvir-PC ~
$ ./test
Enter a string: sdjkfjskfjaskd

"sdjkfjskfjaskd" is an invalid entry. Valid responses are: "Random", "Database", or "Both": Both

Your string is: Both

Sukhvir@Sukhvir-PC ~
$ ./test
Enter a string: Both

Your string is: Both

Upvotes: 3

Related Questions