2015-09-04 49 views
0

我剛開始學習c,並且正在閱讀有關輸入的內容。假設我需要一個c程序,用於識別您輸入的是數字還是字符串(不只是一個字符),然後打印出來。 Somethihng這樣的:確定輸入是數字還是字符串,然後將其打印回來

int input, is_digit; 
    is_digit = scanf("%d", input); 
    printf("Please enter a digit or a string and then a newline\n"); 
    if (is_digit) 
    printf("You entered the digit: %d", &input); 
    else 
    printf("You entered the string: %s", &input); 

這不起作用,如預期,但我寫它給的什麼,我試圖完成一個想法。

你會如何在C中做到這一點?

回答

1

您需要先將所有輸入作爲字符串,然後解析此輸入以檢查它是否爲數字。在失敗的情況情況下,你可以確信,只要輸入是字符串 -

對下面的演示代碼看看 -

fgets(s, sizeof(s), stdin); 
valid = TRUE; 
for (i = 0; i < strlen(s); ++i) 
{ 
    if (!isdigit(s[i])) 
    { 
     valid = FALSE; 
     break; 
    } 
} 
0

首先,使用scanf函數時%d格式進行掃描,你會得到執行下列操作之一:然後

  1. 掃描一個int,並且不需要檢查
  2. 無限循環 - 因爲錯誤的用戶輸入,然後不需要檢查兩種。

如果你想掃描用戶輸入,你應該使用一些其他的功能,如getchar。

<ctype.h>函數庫裏面有一個函數isdigit()可以幫助您遍歷一個字符串並確定一個char是否代表一個int或不是here

例子:

char* str = "abc1"; 
int counter=0; 
while(counter < 4){ 
    if(isdigit(*(str+counter))){ 
    printf("digit") 
    }; 
    counter++; 
} 
0

您可以使用getchar()ungetc()組合看標準輸入的第一個字符,確定它是否是使用isdigit()一個數字,然後把它放回流和閱讀與相應的scanf

0

首先你必須問給用戶之前讀取輸入給用戶,那麼:

printf("Please enter a digit or a string and then a newline\n"); 
is_digit = scanf("%d", &input); 

其次,scanf想要一個指針爲int,在%d格式的話,那麼

scanf("%d", &input); 

三,printf,打印一個int,希望值,則:

printf("You entered the digit: %d\n", input); 

四,你不能打印一個字符串(%s)傳遞一個int變量,那麼你的代碼是完全錯誤的。

一個簡單的解決辦法是,使用isdigit標準功能,這

int main() 
{ 
    char buffer[128]; 
    int i=0; 
    printf("Please enter a digit or a string and then a newline\n"); 
    scanf("%s", buffer); 

    // Checks until the end of string that all chars are digits 
    while ((buffer[i] != '\0') && (isdigit(buffer[i]) != 0)) 
    { 
     i++; 
    } 

    // If index of buffer doesn't point to the end of string, means that a non digit char was found 
    if (buffer[i] != 0) 
    { 
     printf("You entered a string\n"); 
    } 
    else 
    { 
     printf("You entered digits\n"); 
    } 

    return 0; 
} 
0

您收到scanf函數以ASCII格式輸入,見Ascii Table

所有數字(0-9)都在ascii值之間:48-57(十進制)。

你應該首先輸入一個數字/字符並以整數格式(%d)打印出來。將它與ascii表進行比較。只是爲了得到它的感覺。

當你這樣做後,你應該繼續你的任務。考慮到你希望能夠解釋字符和數字,我會用字符串而不是數字來讀取。請參閱scanf,瞭解如何讀取字符串。

聲明一個預定大小的字符。並且一定不要用scanf溢出它。

那麼應考慮以下因素:

  1. 如果有ATLEAST一個字符,這不是一個數字,你應該考慮它的字符串。

簡而言之,您將創建一個while循環(或for循環),只要找到null終止符就會中斷循環。這是字符串的結尾。

在循環中,您有一個每增加一個int(從0開始)的int值。這個int是一次讀取一個字符的索引。繼續閱讀字符,每當有一個ascii值不是一個數字(參見上面的ascii-values),您將設置一個標誌來指示它是一個字符串。這將會讓你在賽道上獲得成功。

相關問題