How do I compare an input in char with an interval (0 to 9) without specifying individual conditions?

Asked

Viewed 292 times

5

I’m doing a show that reads a string and want to ignore the spaces and letters that the user type (but I have to read the letters i and p and the mathematical symbols +-/*^).

What I have achieved so far is to ignore only spaces. I thought that instead of ignoring what I do not want, I accept only 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);

}

2 answers

4


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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I gave a simplified and modernized. Note that checking loose characters has not much to do but compare one by one. Of course I could create a solution with a array of valid characters, but I don’t think it’s worth it in this case, it’s shorter, but it might not be as good in performance.

To check the preferred digits use a ready function (isdigit()). Could also compare by a track (t[i] >= '0' && t[i] <= '9') which should be the exact implementation of isdigit().

I got a problem that prevents the correct functioning in some situations that is the lack of completion of the string which should always end with a null. Also now the loop will even find a null, after all the string can be less than 10 characters, without this check would pick up trash in such cases.

  • I did it separately without using isdigit (I didn’t understand what it’s for) and it worked, but when printing the vector on the screen always print a P0 at the end. You know why this happened?

  • No, I don’t know what you did.

  • 1

    The isdigit is used to check if the character passed is a digit (i.e., if it is between 0 and 9).

  • isdigit in some implementations is a query to a hash table. This allows the operation to be performed in a command.

2

#include <stdio.h>  // para printf, fgets
#include <string.h> // para strchr

int main() // tipo de 'main' e' 'int'
{
   // variavel de controle do 'for' que anda no buffer de entrada (lido do teclado)
   int i;

   // variavel de controle do 'for' que anda no buffer de saida (caracteres validos)
   int c;

   // buffer para leitura de linha
   char t[10];

   // buffer de saida, apenas com os caracteres lidos que sao validos
   char r[10];

   // tabela de caracteres validos
   char validChars[] = "01234567890ip+-/*";

   // ponteiro usado como resultado da chamada a 'strchr'
   char* p;

   // leitura de uma linha do teclado
   // no final do buffer vai ter '\n' e '\0'
   // portanto na verdade vai ter no maximo 8 caracteres validos
   fgets(t, 10, stdin);

   // inicializa os indices dos buffers de entrada 'i' e saida 'c'
   // verifica se cada caracter lido no 'fgets' esta' na tabela 'validChars'
   // para no 0 binario que marca o fim do buffer de entrada
   for (i = 0, c = 0; i < 10 && t[i] != 0; i++)
   {
       // strchr procura o caracter 't[i]' na tabela 'validChars'
       // se o caracter 't]i]' for encontrado, 'p' aponta para o caracter na tabela
       // se o caracter nao for encontrado, 'p' fica valendo NULL
       p = strchr(validChars, t[i]);

       if (p != NULL)
       {
           // ok, caracter e' valido, entao acumula no buffer de saida
           r[c++] = t[i];
       }
   }

   // marca final da string de saida
   r[c] = 0;

   // grava string de saida
   printf("%s", r);

   // nao precisa 'return 0;' porque e' o default
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.