简体   繁体   English

如何检查C中输入的字符串格式是否正确?

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

A want to check if input string is in right format想检查输入字符串的格式是否正确

"%d/%d"

For example, when the input will be例如,当输入将是

"3/5"
return 1;

And when the input will be什么时候输入

"3/5f"
return 0;

I have idea to do this using regex, but I had problem to run regex.h on windows.我有想法使用正则表达式来执行此操作,但我在 windows 上运行 regex.h 时遇到了问题。

It is not completely clear what you mean by the format "%d/%d" .格式"%d/%d"的含义并不完全清楚。

If you mean that the string should be parsed exactly as if by sscanf() , allowing for 2 decimal numbers separated by a / , each possibly preceded by white space and an optional sign, you can use sscanf() this way:如果你的意思是字符串应该像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;
}

If the format is correct, sscanf() will parse both integers separated by a '/' but not the extra character, thus return 2 , the number of successful conversions.如果格式正确, sscanf()将解析由“/”分隔的两个整数,但不解析额外字符,因此返回2 ,即成功转换的次数。

Here is an alternative approach suggested by Jonathan Leffler :这是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';
}

If you mean to only accept digits, you could use character classes:如果你只想接受数字,你可以使用字符类:

#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];
}

How to check if input string is in correct format... ?如何检查输入字符串的格式是否正确...?

A simple test is to append " %n" to a sscanf() format string to store the offset of the scan, if it got that far.一个简单的测试是将 append " %n"转换为sscanf()格式字符串以存储扫描的偏移量(如果扫描到那么远)。 Then test the offset to see if it is at the end of the string.然后测试偏移量,看看它是否在字符串的末尾。

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