2016-07-29 87 views
0

我有這個功能,檢查輸入是否像d1,d7,d65,等 - 意味着它以一個「d」開頭,然後有一個數字。從字符串獲取字符後的數字?

我想檢查一下它的結構,然後返回之後的d

什麼是最有效的方法呢?只能使用scanf嗎?

+2

你在尋找什麼樣的效率?可讀性,可維護性,代碼大小,內存,執行時間? – Martin

+0

你能否提供[mcve]? – xenteros

+0

對不起,謝謝,代碼運行在一個微小的微處理器上,所以代碼行少,並且使用內存。 – Curnelious

回答

2

您可以使用sscanf並檢查返回值,如果它返回1,則表示已成功讀取整數(通過%d) - 並且它與您需要的格式匹配;否則t不具有所需的格式。


int read_fmt(char t[], int *n) 
{ 
    return sscanf(t, "d%d", n); 
} 

int main() 
{ 
    char t[] = "d8787"; 
    int n = 0; 
    if(read_fmt(t, &n) == 1) 
    { 
     printf("correct format, n = %d\n", n); 
    } 
    else 
    { 
     perror("incorrect format\n"); 
    } 
} 
+0

優秀。不知道爲什麼人們投票。我沒有使用2行的函數,並且它按預期工作。 – Curnelious

0

由於結構是微不足道的一些簡單的檢查和strol應該做的伎倆,是這樣的:

#include <stdio.h> 
#include <stdlib.h> 
#include <stdbool.h> 

const char* input = "d1,d7,d65,d171"; 
bool error = false; 
const char* ptr = input; 

while (*ptr != '\0') 
{ 
    // not starting with d so break with failure 
    if (*ptr != 'd') { error = true; break; } 
    // we must find a sequence of "number,..." or "number\0" 
    else 
    { 
    // not any character available, break with failure 
    if (++ptr == '\0') { error = true; break; } 
    else 
    { 
     int v = strtol(ptr, &ptr, 10); 

     // add error check for strtol 

     printf("found: %d\n", v); 

     // skip comma 
     if (*ptr && *ptr == ',') ++ptr; 
    } 
    } 
} 

printf("error = %d\n", error); 

但你必須照顧所有不同的邊緣情況,以確保正確的行爲。

+0

用'int v = strtol(ptr,&ptr,10)'結尾使用相同的指針;'否定測試_no conversion_的能力。 – chux