2016-02-05 91 views
0

我無法弄清楚如何做到這一點。我有一個帶有顏色名稱或十六進制代碼(#ffffff)的字符數組,它不會將正確的RGB值返回給main,也不會通過「#」讀取6個十六進制數字。我真的很生疏,大約一年沒有編碼,所以請批評你看到的任何內容。十六進制顏色代碼到RGB數字

/**readColor() 
Converts the decimal values, color name or hex value read from 
the input stream to the 3 byte RGB field 

Returns the rgb values if successful. On error prints errmsg and 
exits. 
**/ 
color_t readColor(FILE *infile, char *errmsg) 
{ 
int rc, red, green, blue; 
char alpha[7] = {}; 
int i=0; 

rc = fscanf(infile, "%d %d %d\n", &red, &green, &blue); 
if(rc == 3){ 
    if(red>=0 && red<=255 && green>=0 && green<=255 && blue>=0 && blue<=255){ 
     return((color_t){red, green, blue}); 
    } 

} 
if (rc != 0){ 
    printf("%s", errmsg); 
    return((color_t){0,0,0}); 
} 


fgets(alpha, 10, infile); 
fputs(alpha); 

i=0; 
if(strcmp(alpha, "white")==0){ 
    return((color_t){255, 255, 255 }); 
} 
else if(strcmp(alpha, "red")==0){ 
    return((color_t){255, 0, 0}); 
} 
else if(strcmp(alpha, "blue")==0){ 
    return((color_t){0, 0, 255}); 
} 
else if(strcmp(alpha, "purple")==0){ 
    return((color_t){128, 0, 255}); 
} 
else if(strcmp(alpha, "black")==0){ 
    return((color_t){0, 0, 0}); 
} 
else if(strcmp(alpha, "green")==0){ 
    return((color_t){0, 255, 0}); 
} 
else if(strcmp(alpha, "orange")==0){ 
    return((color_t){255, 128, 0}); 
} 
else if(strcmp(alpha, "yellow")==0){ 
    return((color_t){255, 255, 0}); 
} 
else if(alpha[0] == "#"){ 
    alpha++; 
    if(sscanf(alpha, "%2x%2x%2x", &red, &green, &blue)!= 3){ 
     printf("%s", errmsg); 
    } 
    else{ 
     return((color_t){red, green, blue}); 
    } 
} 
else{ 
    printf("%s", errmsg); 
} 

return((color_t){0, 0, 0}); 
} 

回答

0
alpha[0] == "#" 
      ^^ 
      double quotes for string literal 

應該

alpha[0] == '#' 
      ^^ 
      single quotes for character literal 

單個字符比較的字符串字面量是一個約束衝突(感謝@AnT您指出術語錯誤),編譯器不應該允許。而是將單個字符與字符字面值進行比較。

+0

「比較單個字符與字符串文字」是違反約束條件,即通常所說的「編譯錯誤」。像往常一樣,針對此違規的特定診斷可能會受到編譯器的警惕。 – AnT

+0

我想。但是,如果編譯器只發出一個警告(無論出於何種原因),並且用戶不會看它... – owacoder

+0

首先,它僅發出警告,因爲用戶忘記指定「-pedantic-errors」標誌(強制用於標準C開發;假設GCC)。其次,警告是一種診斷,不比任何其他診斷都好。 – AnT

1

您可以使用%x格式說明符來讀取十六進制值。用兩個0填充的寬度,將不需要進行範圍測試。 例如

int r, g, b; 
if(3 == scanf("#%02x%02x%02x", &r, &g, &b)) 
{ 
    printf("Red : %3d (%02x)\n", r, r); 
    printf("Green : %3d (%02x)\n", g, g); 
    printf("Blue : %3d (%02x)\n", b, b); 
} 
相關問題