0

I'm a rookie programmer trying to run a simple code on VS code.

#include<stdio.h>

int main()
{
char* a;

printf("Enter a char");
scanf("%s",&a);

if (a = "yes")
{
    printf("Number is 30");
}
else if (a = "no")
{
    printf("Number is 50");
}
else{
    printf("oops");
}

return 0;
}

I guess looking at the code you guys can figure out what I'm trying to do, if the user enters "yes", a specific sentence need to be displayed and similarly for "no". The problem here is whatever I write in the input, it will always print the first statement, "Number is 30". I've tried running similar codes but ended up with the same output.

If possible, please explain me how to use char,strings,arrays with if-else statements.

  • `char* a` -> `char a[100];`, `scanf("%s",&a);` -> `scanf("%s", a);`, `a = "yes"` -> `strcmp(a, "yes") == 0`. – Jabberwocky Nov 23 '21 at 08:45
  • `a` is uninitialized, so passing it to `scanf` as you are is undefined behavior. `if (a = "yes")` is assignment, not comparison. Use `strcmp` to compare strings. – Retired Ninja Nov 23 '21 at 08:45
  • Also read this: https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c, as well as the chapter dealing with strings in your learning material. – Jabberwocky Nov 23 '21 at 08:46
  • 1
    Trying to ad-hoc learn C is a lost cause, especially considering how easy it is to write code that "compiles" but is nowhere close to correct. [Get a good book](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) and work through through it one step at a time. – WhozCraig Nov 23 '21 at 08:56
  • There's lot of fundamental problems with this code. Check out my string-handling FAQ here: [Common string handling pitfalls in C programming](https://software.codidact.com/posts/284849) Your problem is bug #3 though you also have a stray `&` in the scanf. – Lundin Nov 23 '21 at 09:22
  • @WhozCraig That list contains more bad books than good ones. I wouldn't recommend anyone to use it. – Lundin Nov 23 '21 at 09:25
  • Does this answer your question? [How do I properly compare strings in C?](https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c) – Nick is tired Dec 10 '21 at 22:02

3 Answers3

3

There are several misunderstandings in the posted code.

First there is a misunderstanding of char versus string. A char is for instance a single letter, a single special character like ., ;, etc. (see note1) while a string is a serie of chars. So

'y' is a char
"yes" is a string

You print "Enter a char" but from the code it's obvious that you really want "Enter a string".

This leads to the next problem. To input a string using scanf you need to pass a "pointer to char". Your code pass "a pointer to pointer to char" due to the &. Further the passed pointer must point to some memory. So you need:

char a[10];   // Make it an array of char so that it can hold a string

printf("Enter a string, max 9 characters");
scanf("%9s", a);  // No & before a and width specifier used to avoid buffer overflow

Now this part

if (a = "yes")

is not the way to compare two strings in C. For that you need the function strcmp - like:

if (strcmp(a, "yes") == 0)

Putting it together it's like:

int main()
{
    char a[10];
    printf("Enter a string, max 9 characters");
    scanf("%9s", a);
 
    if (strcmp(a, "yes") == 0){
        printf("Number is 30");
    }
    else if (strcmp(a, "no") == 0)
    {
        printf("Number is 50");
    }
    else
    {
        printf("oops");
    }

    return 0;
}

That said, I don't understand why you print stuff like: "Number is 30" but that's kind of irrelevant here.

note1: The type char is actually an integer type, i.e. a number, but the common use is to map these numbers to characters using ASCII encoding.

mch
  • 9,424
  • 2
  • 28
  • 42
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • Thank you so much! Your solution worked for me! To explain why I used such irrelevant statements there is because the original code was not this. I was practicing if-else statements with integers first. So that worked, and then I tried with characters, I didn't feel the need to change the print statements since it wouldn't change the overall outcome of the program. Also, you forgot to mention that I should include the header file. But no worries, I figured it out. Thank you for your response. –  Nov 23 '21 at 15:03
-1

There are different ways to initialize a variable to access C string.

char *char_ptr = "Hello";

This initializes char_ptr to point to the first character of the read-only string "Look Here".A C string initialized through a character pointer cannot be modified. When a C string is initialized this way, trying to modify any character pointed to by char_ptr is undefined behaviour. An undefined behaviour means that when a compiler encounters anything that triggers undefined behaviour, it is allowed to do anything it seems appropriate.

A more convenient way to define strings that can be modified is to use:

char str[];

This way you can modify any character in the C string

p.s you also need to use strcmp() for the if statement

Alireza81
  • 1
  • 1
  • 1
    `char str[];` would not compile – klutt Nov 23 '21 at 09:57
  • of course it would not compile if used exactly like that :/ just define n = 10; and use char str[n]; – Alireza81 Nov 23 '21 at 11:51
  • So what you're saying is that it would compile if you change it to for instance `char str[10]`? – klutt Nov 23 '21 at 12:03
  • oh , i see that og also hasn't used strcmp ,well if that is used then it would compile with no problem ,my bad :) – Alireza81 Nov 23 '21 at 12:34
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 23 '21 at 14:22
-2

You can take string input in C using

scanf(“%s”, str);

And to compare the string you need to use:

strcmp(str1, "yes");
Spad223
  • 9
  • 8