How do I compare an input in char with a range (0-9) without needing individual conditions?

Question:

I'm making a program that reads a string and I want to ignore the spaces and letters the user types (but I have to read the letters iep and the math symbols +-/*^).

What I've achieved so far is just ignoring spaces. I thought that instead of ignoring what I don't want, I only accept what I want. So I need to know how to compare with an interval.

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

  void main()
  {
    char t[10];
    char r[10];
    fgets(t, 10, stdin);
    int i = 0;
    int c = 0;
    for (i=0; i<10; i++){
        if (t[i] !=' '){
            r[c]=t[i];
            c++;
        }
    }
    printf("%s", r);

}

Answer:

You can do it like this:

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

int main() {
    char t[10];
    char r[10];
    fgets(t, 10, stdin);
    int c = 0;
    for (int i = 0; i < 10 && t[i] != 0; i++) {
        if (isdigit(t[i]) || t[i] == 'i' || t[i] == 'p' || t[i] == '+' || 
                t[i] == '-' || t[i] == '*' || t[i] == '/' || t[i] == '^') {
            r[c++] = t[i];
        }
    }
    r[c] = '\0';
    printf("%s", r);
}

See working on ideone . And on repl.it. Also posted on GitHub for future reference .

I gave it a simplified and modernized experience. Note that checking for single characters doesn't have much to do other than compare one by one. Of course I could create a solution with an array of valid characters , but I don't think it's worth it in this case, it gets shorter, but it might not be as good in performance.

To check the digits I prefer to use a ready-made function ( isdigit() ). It could also compare by a range ( t[i] >= '0' && t[i] <= '9' ) which must be the exact implementation of isdigit() .

I fixed a problem that prevents it from working correctly in some situations, which is the lack of completion of the string that must always end with a null. Also now the loop will even find a null, after all the string can be shorter than 10 characters, without this check it would get garbage in these cases.

Scroll to Top