Search code examples
cvariablesinputstore

How do you store user input as a variable in c?


I am a very newbie programmer, and have no clue whatsoever what I'm doing. besides reading documentation.

My program isn't giving the user time to input the unwires right away, its just saying the answer for no. What did I do wrong?

I made this program to be a funny joke for my friends (like an AI gone wrong)

Here is my code:

#include <stdio.h>

int main() {

    int yorn;

    printf("do you have friends? please awnser yes or no.");
    scanf("%d", &yorn );

    if (yorn = "yes") {
        printf("no, you dont. please reload the program if you want to change your awnser.");
    }
    else if (yorn = "no") {
        printf("i can be your friend. your BEST friend.");
    }
    return 0;
}

Solution

  • For comparison, you have two use strcmp not =. Also, you are taking int type for yorn and comparing with the string. Change yorn type to char[] and read as %s in scanf.

    Change your code to following the code. look closely to understand it:

    int main() {
    
        char yorn[20]; //set max size according to your need
    
        printf("do you have friends? please awnser yes or no.");
        scanf("%19s", yorn); // Use %s here to read string.
    
        if (strcmp(yorn, "yes") == 0) { //Use ==
            printf("no, you dont. please reload the program if you want to change your awnser.");
        }
        else if (strcmp(yorn,"no") == 0) { // Use ==
            printf("i can be your friend. your BEST friend.");
        }
        return 0;
    }