cif-statementcs50c-stringsstrcmp

How can I use strcmp properly when I have more than two strings?


So the aim of my code is to get an input, add the digits of the input, then add the sum to the input and do this until the number is over 1000. There is no problem with calculation however at the beginning of my code, I ask a yes or no question and use strcmp to compare the answers, but it doesn't go as I plan.

Here is my code:

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>


void calculate(int number);

int main(void)
{
    //ask to begin
    char answer[20];
    printf("Type yes or no (y/n) if you want to have the sum of the digits; ");
    scanf("%s", answer);

    //check the answer
    if (strcmp(answer, "y") || strcmp(answer, "Y") || strcmp(answer, "yes"))
    {
        //ask for a number
        int number = get_int("Write your number here: ");

        //calculation
        calculate(number);
        return 0;
    }

    //answer is no or invalid
    else
    {
        printf("bye\n");
        return 1;
    }
}

void calculate(int n)
{
    int c = 0, sum = 0, r;
    do
    {
        sum = n;
        while (n != 0)
        {
            r = n % 10;
            sum = sum + r;
            n = n/10;
        }
        n = sum;
        printf("Sum of the digits of your number = %d\n", sum);
        c++;
    } while (sum < 1000);
    printf("Number of calculations %d\n", c);
}

If I give "y", "yes", or "Y" as input to the yes or no question, this appears: enter image description here

If I give any other input to the yes or no question, this appears: enter image description here

Whatever input I give, the program still runs and asks for a number. How can I properly use strcmp here or is there any other way I can accomplish this?


Solution

  • If two strings are equal each other then the function strcmp returns 0.

    From the C Standard (7.23.4.2 The strcmp function)

    3 The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

    So you need to write

    if (strcmp(answer, "y") == 0 || strcmp(answer, "Y") == 0 || strcmp(answer, "yes") == 0)
    

    Pay attention to that it will be safer to write the call of scanf the following way

    scanf("%19s", answer);