2017-05-27 101 views
-3

C有沒有一種優雅的方式來檢查給定的字符串是否是「雙」? 如果變量的類型是double,但是如果字符串包含實數,則不適用。 例如:檢查一個輸入字符串是否是一個實數C

char input[50]; 
printf("please enter a real number: \n"); 
scanf("%s", input); 
if (is_double(input)) { 
    //user entered "2" 
    return true; 
    //user entered "2.5" 
    return true; 
    //user entered "83.5321" 
    return true; 
    //user entered "w" 
    return false; 
    //user entered "hello world" 
    return false; 
} 
+3

你可以使用['strtod'(http://en.cppreference.com/w/c/string/byte/strtof)並查看它是否可以轉換完整的字符串。 –

+1

https://stackoverflow.com/a/456314/971127 – BLUEPIXY

+1

順便提一句,'fgets(input,sizeof(input)-1,stdin);'比scanf(「%s」,輸入)要好;' –

回答

1

您需要定義如果121e23是你雙打。那麼-4z12.3,?因此,請說明什麼是可接受的和禁止的輸入(提示:在紙上使用EBNF可能會有所幫助)。


注意strtod可以使用,並且可以給指針到最後解析字符。

所以

char* endp=NULL; 
double x = strtod(input, &endp); 
if (*endp == 0) { // parsed a number 

而且sscanf(你需要包括<stdio.h>)返回掃描的項目數,並接受%n(加入#include <stdlib.h>靠近你的文件的開頭....之後)給出當前的字節偏移量。

int pos= 0; 
double x = 0.0; 
if (sscanf(input, "%f%n", &x, &pos)>=1 && pos>0) { // parsed a number 

您也可以使用正則表達式(regcomp(3) & regexec(3) ...)或parse您手動

串留作練習。

PS。請仔細閱讀鏈接的文件。

+0

試圖使用'strtod',但對於一些原因我得到'x = -var-create:無法在調試器中創建變量對象..「 – Avishay28

+0

我不明白上面的評論。你的*編譯器*抱怨嗎?什麼是'var'或'create'? –

+0

編譯器沒問題,得到'strtod'結果的變量設置不正確。我從調試器得到這個消息。 – Avishay28

1

只要你不是讓科學記數法:

#include <ctype.h> 
#include <string.h> 
#include <stdbool.h> 

bool is_double(const char *input) 
{ 
    unsigned long length = strlen(input); 
    int num_periods = 0; 
    int num_digits = 0; 
    for (unsigned int i = 0; i < length; i++) 
    { 
    if (i == 0) 
    { 
     if (input[i] == '-' || input[i] == '+') 
      continue; 
    } 
    if (input[i] == '.') 
    { 
     if (++num_periods > 1) return false; 
    } 
    else 
    { 
     if (isdigit(input[i])) 
     { 
     num_digits++; 
     } 
     else 
     return false; 
    } 
    } /* end for loop */ 
    if (num_digits == 0) 
     return false; 
    else 
     return true; 
} 
+0

考慮替換'if(num_periods == 0){num_periods = 1; } else返回false;'用'if(num_periods ++!= 0)返回false;'。它更緊湊 - 但不會改變功能。目前,該代碼在數字之前不處理標誌。你明確地說你不處理指數。 –

相關問題