Home > Blockchain >  How to check if input string is in correct format in C?
How to check if input string is in correct format in C?

Time:11-30

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.

CodePudding user response:

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. 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");
}

CodePudding user response:

It is not completely clear what you mean by the format "%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:

#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.

Here is an alternative approach suggested by 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];
}
  •  Tags:  
  • c
  • Related