2015-01-21 14 views
-4

我嘗試運行此程序並使用枚舉從用戶處獲取一個字符串,並將其作爲int 將數組作爲int我試圖讓從用戶scanf函數的數據,比,而不是由它的阿甘向前c編程嘗試獲取scanf中的枚舉詞,並將其放在int數組中

乳寧的程序是這樣的代碼:

#include <stdio.h> 
#include <string.h> 


int main() 
{ 
    enum color { RED = 1, BLUE, BLACK }; 
char choice[6]; 
int colors[21]; 
int i, counter_red = 0, counter_blue = 0, counter_black = 0, x; 


for (i = 0; i < 20; i++) 
{ 
    printf("Write your favorite color : RED, BLUE or BLACK\n"); 
    scanf_s("%s", &choice); 


    if (strcmp(choice, "BLACK") == 0) 
    { 
     colors[i] = 3; 
    } 

    if (strcmp(choice, "BLUE") == 0) 
    { 
     colors[i] = 2; 
    } 

    if (strcmp(choice, "RED") == 0) 
    { 
     colors[i] = 1; 
    } 



} 


for (x = 0; x < 20; x++) 
{ 
    if (colors[x] == 1) 
    { 
     counter_red++; 
    } 
    else if (colors[x] == 2) 
    { 
     counter_blue++; 
    } 
    else if (colors[x] == 3) 
    { 
     counter_black++; 
    } 
} 
if (counter_red > counter_blue && counter_red > counter_black) 
{ 
    printf("%s", "The most popular color is: RED\n"); 
} 
else if (counter_blue > counter_red && counter_blue > counter_black) 
{ 
    printf("%s", "The most popular color is: BLUE\n"); 
} 
else if (counter_black > counter_red && counter_blue < counter_black) 
{ 
    printf("%s", "The most popular color is: BLACK\n"); 
} 
printf("RED: %d % \nBLUE: %d %\nBLACK : %d % \n", counter_red * 5, counter_blue * 5, counter_black * 5); 


return 0; 

} 
+1

我推薦先學習C基礎知識,網上有很多C的教程,只是Google。 – theadam 2015-01-21 08:36:58

回答

0

您使用scanf_s錯誤。首先,數組choice在傳遞給函數時衰減爲指針,所以不應該在那裏使用地址 - 運算符&。其次,更重要的是,對於格式字符串中的每個格式代碼,scanf_s需要兩個參數:轉換的目的地和目的地的大小。

由於您不通過大小,所以當scanf_s函數試圖獲取該堆棧的值時,您有undefined behavior

您的電話應該像

scanf_s("%s", choice, sizeof(choice)); 

作爲一個側面說明:其實你不使用定義枚舉。要使用它,你應該例如

... 
enum color colors[20]; 
... 
colors[i] = RED; 

作爲另一個側面說明:您只使用了20項colors陣中,但是你把它定義爲21項。

+0

非常感謝nuch p.s我強制使用scanf_s becoas即時通訊使用vs ... p.s.2如果我不使用scanf_s我是否需要這樣做呢? scanf(「%s」,choice,sizeof(choice)); ?或者我需要像這樣做scanf(「%s」,&choice);? – 2015-01-21 12:23:11

+0

@H_meir簡單的'scanf'不使用size參數,並且您仍然不應該在字符串的數組(或指針)上使用操作符'&'的地址。 – 2015-01-21 12:29:00