2010-04-14 107 views

回答

3

請參閱stdio.h中的scanf()函數。它需要一個格式說明像printf()和指針變量與用戶輸入存儲在

2

使用scanf()

格式:int scanf (const char * format, ...);

Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.

實施例:

#include <stdio.h> 
int main(void) 
{ 
    int n; 
    printf("Enter the value to be stored in n: "); 
    scanf("%d",&n); 
    printf("n= %d",n); 
} 

然而看看this.

0

對於C來說,你看起來相當新,所以讓我給Prasoon的答案添加一些內容,這是非常正確和完整的,但對於初學者來說可能很難理解。

當使用scanf(const char * format,...);在他爲例,Prasoon使用:

scanf("%d",&n); 

在使用這一點,「%d」表示你要讀取一個整數(見wikipedia完整格式列表)。

第二個參數(注意......表示可以發送任意數量的參數)表示您要在其中存儲用戶條目的變量的地址

1

'這很有趣 - 目前爲止的兩個答案都暗示scanf();我不會。

當一切正常時,scanf()是確定的。當事情出錯時,恢復往往很難。

我通常會使用fgets()首先將一行的用戶信息讀入緩衝區(字符數組)。然後我會使用sscanf()從緩衝區中收集信息到目標變量中。最大的好處是,如果用戶輸入'12Z',當你想讓他們輸入兩個數字時,你可以告訴他們你看到了什麼,以及爲什麼它不是你想要的更好。用scanf(),你不能那樣做。

+2

@Jonathan:也許你錯過了我在帖子中給出的鏈接。 – 2010-04-14 03:44:00

+0

@Prasoon:是的 - 我確實想念它,因爲你沒有在帖子中解釋爲什麼你使用scanf()的建議不一定是個好主意。 – 2010-04-14 03:55:18

相關問題