簡體   English   中英

如何檢查C中輸入的字符串格式是否正確?

[英]How to check if input string is in correct format in C?

想檢查輸入字符串的格式是否正確

"%d/%d"

例如,當輸入將是

"3/5"
return 1;

什么時候輸入

"3/5f"
return 0;

我有想法使用正則表達式來執行此操作,但我在 windows 上運行 regex.h 時遇到了問題。

格式"%d/%d"的含義並不完全清楚。

如果你的意思是字符串應該像sscanf()一樣被解析,允許 2 個由/分隔的十進制數字,每個數字前面可能有空格和一個可選的符號,你可以這樣使用sscanf()

#include <stdio.h>

int has_valid_format(const char *s) {
    int x, y;
    char c;
    return sscanf(s, "%d/%d%c", &x, &y, &c) == 2;
}

如果格式正確, sscanf()將解析由“/”分隔的兩個整數,但不解析額外字符,因此返回2 ,即成功轉換的次數。

這是Jonathan Leffler建議的另一種方法:

#include <stdio.h>

int has_valid_format(const char *s) {
    int x, y, len;
    return sscanf(s, "%d/%d%n", &x, &y, &len) == 2 && s[len] == '\0';
}

如果你只想接受數字,你可以使用字符類:

#include <stdio.h>

int has_valid_format(const char *s) {
    int n = 0;
    sscanf(s, "%*[0-9]/%*[0-9]%n", &n);
    return n > 0 && !s[n];
}

如何檢查輸入字符串的格式是否正確...?

一個簡單的測試是將 append " %n"轉換為sscanf()格式字符串以存儲掃描的偏移量(如果掃描到那么遠)。 然后測試偏移量,看看它是否在字符串的末尾。

int n = 0;
int a, b;
//           v---v----- Tolerate optional white spaces here if desired.
sscanf(s, "%d /%d %n", &a, &b, &n);
if (n > 0 && s[n] == '\0') {
  printf("Success %d %d\n", a, b);
} else {
  printf("Failure\n");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM