2011-07-22 19 views
0

Helllo字符串語句,我還是新的編程,有一個問題有關,而使用用戶輸入與我進行了我似乎無法找到我在做什麼研究使用if語句錯誤? 以下是我發佈的簡單乘法計算器。如果使用帶有字母和用戶輸入

#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"); 
printf("\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; }

+0

請告訴我們你有什麼期待,然後什麼洙發生 –

回答

1

我認爲你正在使用的格式錯誤%i閱讀charscanf("%i", &userinput);

我認爲這是一個更好的使用@NSString,而不是簡單的字符(我甚至不能確定在ObjC會發生什麼如果你寫char a = "asd",因爲你給人一種char一個char[]值)。在這種情況下,由於字符串是指針,所以you cannot use == to compare them。您可以改用isEqualToStringisEqualTo。如果你對兩者的區別感興趣,看看this post會有所幫助。

0

在C中,你不能使用==比較字符串,那麼你將不得不使用這樣的函數strcmp(),像這樣的:(!)

if (!strcmp(userinput, yesvari)) { 
    //etc. 
} 

的一聲被使用,因爲strcmp()實際上返回0時兩個字符串匹配。歡迎來到C的精彩世界!

+0

謝謝你們多,我正在literately從一本書,堆棧溢出壽學習是一個很大的幫助 –

2

您不正確地%i掃描的字符,你需要使用strcmp對它們進行比較。如果您正在尋找來自用戶的字符串,你需要使用%s,你需要的字符緩衝區大到足以容納輸入。

試試這個

//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"); 
} 
+0

感謝順便說一句,我得到的一切ü說除了對(INT I = 0; I <3;我++) userinput [I] = tolower的(userinput [I]); –

+0

你只是說程序只是掃描小寫字符? –

+0

'tolower的()'將小寫userinput所以,如果他們進入「YES」或「是」不會失敗。它一次只能在一個角色上工作,所以你只需要遍歷每個角色。另外你的例子是在所有C中,沒有任何Objective-C調用會使你想要做的事更容易。 – Joe

相關問題