char array in if statement doesnt work

+1 Jacobs . · August 26, 2014
Hello, I have a maybe bizarre problem for you but i was thinking a lot but i couldn't figure it out. 
So I decided to post it here.

Actually it's part of bigger program but i wrote the problematic part into a new file for better reading.
Here is my code:


#include <stdio.h>
#include <stdlib.h>

int main()
{

    char input[10];

    scanf(" %s", input);

    if(input == 'Y' || input == 'N')
    {

        printf("It's working");

    }else{
        printf("It doesn't work");
    }

    return 0;
}

At the start program waits for input from user, when you type in Y/N or something else the if statement checks what you typed, the problem is that the if statement does not run either you type Y/N or something else. It always runs the else statement. I tried same thing with an integer and it works. So i realized that problem is between char array and if statement but I dont know how to fix it.

Post a Reply

Replies

Oldest  Newest  Rating
0 Jm DGreat · October 17, 2014
Hi Bucky! How can i Test the whole string that i Input in Array? :)
+1 Jacobs . · August 26, 2014
Thanks bucky!

Reason why i used array is because in my original program the user isnt only supposed to enter single characters but sometimes whole words.
But when i test words like if(input =="word") and characters like (input[0] == 'S') it works.
+2 Bucky Roberts · August 26, 2014
There are a couple problems. I left my notes in the comments. 

#include <stdio.h>
#include <stdlib.h>

int main()
{
    // you don't need to use an array for just one character, but this will still work
    char input[10];

    // scan character into the first element of the array
    scanf(" %c", &input[0]);

    // do not test against the entire string, just the first letter
    if(input[0] == 'Y' || input[0] == 'N')
    {
        printf("It's working");

    }else{
        printf("It doesn't work");
    }

    return 0;
}
  • 1

C

106,928 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator