2015-04-03 116 views
1

我有以下代碼:故障與scanf函數(C)

struct punto richiedi_punto() { 
static int count=1; 
struct punto point; 

do { 
printf("Inserire coordinate del punto %i:", count); 
scanf("%d;%d",&point.x,&point.y); 

} while (point.x<0 || point.x>9 || point.y<0 || point.y>9); 
count++; 

return point; 
} 

GCC不發現錯誤,但我得到這樣的警告:

Warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result] 

我試圖找出一個解決方案在谷歌,但我不明白是什麼原因導致此警告。

在此先感謝。

編輯:我注意到,如果我在MonoDevelop控制檯中運行我的程序,我無法插入我的座標(爲什麼?),但是如果我在gnome-terminal中運行它,它通常工作。

+0

從scanf中刪除';'(在2%之間) – 2015-04-03 10:47:15

+0

什麼是x和y的類型?你能給完整的代碼嗎? – Mukit09 2015-04-03 10:47:32

+0

@karma_geek,爲什麼? – 2015-04-03 11:50:13

回答

1

scanf()返回字段數轉換成功,爲您檢查

int fields; 
do { 
    printf("Inserire coordinate del punto %i:", count); 
    fields = scanf("%d;%d",&point.x,&point.y); 
} while (fields != 2 || point.x<0 || point.x>9 || point.y<0 || point.y>9); 

由於@chux指出,上述並不好。這是一個使用sscanf而不是scanf的版本。

#include <stdio.h> 

int main() 
{ 
    int fields, x, y; 
    char inp[100]; 
    do { 
     printf("Inserire coordinate:"); 
     fgets(inp, 100, stdin); 
     fields = sscanf(inp, "%d;%d",&x,&y); 
    } while (fields != 2 || x<0 || x>9 || y<0 || y>9); 
    printf("x=%d, y=%d\n", x, y); 
    return 0; 
} 
+0

'while(fields!= 2 || point.x <0 ....'是一個好主意,但處理'fields!= 2'可能需要一個不同的路徑,然後循環。用戶輸入如「12 x 34」會導致無限循環。 – chux 2015-04-03 13:03:03

+0

@chux這就是爲什麼我討厭'scanf'。 – 2015-04-03 14:29:14

+0

我們可以希望C的下一個版本會發送'gets()'一個叫做'scanf()'? – chux 2015-04-03 14:43:21

-1

Scanf返回輸入no.of成功獲得的值。警告你是忽略該返回值。

所以,你可以使用這樣,

int ret; 
ret=scanf("%d;%d",&point.x,&point.y); 

否則,

(void*)scanf("%d;%d",&point.x,&point.y); 
-1

這意味着你不檢查scanf函數的返回值。
如果只設置了point.x或point.y,則scanf可以返回1;如果沒有設置point.x或point.y,則返回0。

你可以檢查scanf函數的返回值,以消除此警告這樣

int ret = scanf("%d;%d",&point.x,&point.y); 
if (ret != 2) 
{ 
    printf("Error whith scanf"); 
    return 0; 
} 
2

看一看的scanf manual:函數的返回值是你要知道,如果函數成功的唯一途徑。

在這裏,您的編譯器不喜歡您的代碼,因爲您甚至不會查看返回值,因此即使該函數失敗,代碼也會繼續。

這裏的失敗很容易,例如,如果輸入不是數字,或者不包含';'如預期的那樣,或其他。

所以才更換scanf函數一行是這樣的:

if (scanf("%d;%d",&point.x,&point.y) != 2)) {} 

應該安撫GCC,顯示他你關心的返回值。 但最簡潔的解決方案是存儲返回值並根據所做的操作,查看手冊的「返回值」部分以獲取更多信息。