Helllo I am still new to programing and had a question about using if statements while using user input with the research I have conducted i can't seem to find what I am doing wrong? Below is my posted simple multiplication calculator.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
int a ;
int b ;
int c ;
printf("\n");
printf("\n");
printf("Welcome to calculator");
printf("\n");
printf("\n");
printf("what would you like to choose for first value?");
scanf("%d", &a);
printf("\n");
printf("What would you like to input for the second value?");
scanf("%d", &b);
c = a * b;
printf("\n");
pri开发者_运维技巧ntf("\n");
printf(" Here is your product");
printf("\n");
NSLog(@"a * b =%i", c);
char userinput ;
char yesvari = "yes" ;
char novari = "no";
printf("\n");
printf("\n");
printf("Would you like to do another calculation?");
scanf("%i", &userinput);
if (userinput == yesvari) {
NSLog(@" okay cool");
}
if (userinput == novari) {
NSLog(@"okay bye");
}
return 0; }
You are scanning the character incorrectly with %i
and you need to compare them using strcmp
. If you are looking for a string from the user you need to use %s
and you need a character buffer large enough to hold the input.
Try this
//Make sure userinput is large enough for 3 characters and null terminator
char userinput[4];
//%3s limits the string to 3 characters
scanf("%3s", userinput);
//Lower case the characteres
for(int i = 0; i < 3; i++)
userinput[i] = tolower(userinput[i]);
//compare against a lower case constant yes
if(strcmp("yes", userinput) == 0)
{
//Logic to repeat
printf("yes!\n");
}
else
{
//Lets just assume they meant no
printf("bye!\n");
}
I think you are reading a char
using the wrong format %i
: scanf("%i", &userinput);
And I think it is a better to use @NSString instead of simple char (I am not even sure what will happen in ObjC if you write char a = "asd"
, since you are giving a char
a char[]
value) . In that case, since strings are pointers, you cannot use ==
to compare them. You could use isEqualToString
or isEqualTo
instead. If you are interested in the difference between the two, look at this post would help.
In C, you can't compare strings using ==
, so you would have to use a function like strcmp()
, like this:
if ( !strcmp(userinput, yesvari) ) {
//etc.
}
The bang (!) is used because strcmp()
actually returns 0 when the two strings match. Welcome to the wonderful world of C!
精彩评论