• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

help with a small program i am writing in C

MarcMaiden

Android Enthusiast
Jan 13, 2010
590
201
Bay Area, ca
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!
 
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
else
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
 
Upvote 0
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!
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones