help with a small program i am writing in C

Last Updated:

  1. MarcMaiden

    MarcMaiden Well-Known Member This Topic's Starter

    Jan 13, 2010
    Likes Received:
    Basically im trying to make this work (ignore the cheesiness)
    #include "stdfx.h"

    int main()
    char *c; //yes

    printf("Dad, are you free for lunch tomorrow at 12:30? Please type Y or N\nand then hit enter\n");
    scanf_s("%d", &c);

    if( c == "y") { printf("Great! let me know where you feel like eating. I only have about 45 min to eat \nbefore I need to work\n"); }
    else if ( c == "n" ) { printf("Well you can't blame me for trying...maybe another time\n"); }

    return 0;

    is this the correct way of writing it?

    when ever i compile it, it only gives back the "Great" answer. If it isnt clear what im trying to do, I am trying to get it so when he enters "y" it says great, or if he enters any other key it says "well..."

    thanks for your help guys!

  2. liba

    liba New Member

    Oct 4, 2010
    Likes Received:
    try to put the command elseif as c!="y" then you may get the right one
  3. Pryomancer

    Pryomancer Well-Known Member

    Mar 29, 2010
    Likes Received:
    I don't know C, but this is a logical problem, not a language specific one. Change it to if c == y, do this
    and if it's anything else, i.e. not y, do this. I don't know the C code for it, but the java version would be an if statement with an else statement
    Something like
    if (c == y){print out "great...."}
    else (print out "well..."}
  4. jonbonazza

    jonbonazza Well-Known Member

    Jul 13, 2010
    Likes Received:
    Try this:

    Your error is that you are misusing pointers all over the place.

    First off, you declared c as a pointer. you then stored the input in &c (the memory address of c), THEN you compared the POINTER to c to 'y' or 'n'.

    I am a bit rusty on my C (I use C++ and Java more lately), but I think the best thing to do is to

    change your conditional to:

    if(*c == 'y')
    blah blah blah
    else if(*c == 'n')
    blah blah
    blah blah blah...

    I can't remember how exactly scanf_s works tho... Are you required to give it an address? If you do give it an address, does it store the input in the address, or does it dereference the address and store it in the variable itself?

    Last question: Why not just use C++? lol
  5. infomudgeon

    infomudgeon New Member

    Aug 31, 2010
    Likes Received:
    suggestion: declare c as a string
    char c[32]; (then *c is the pointer)
    read the string with "%s" (%d reads a digit)
    convert the input to lower case with c[0]= tolower( C[0] ); (in case 'Y' is entered)
    compare only the first character of the string c[0]
    add a test stmt printf( "%s \n", &c0) to check what you are really using.

    had to get my old K&R out of the bookcase!

Share This Page