Check if a string is composed of digits

Asked

Viewed 407 times

1

I want to check if my strings (which are stored in an array), are integer or not for example a for the fourth row of the matrix have the following code.

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

struct informacaoFicheiroInput{
int id;
int acompanhantes;
char tipo[13];
int entrada;
int saida;
int servico;

};

void toString(struct informacaoFicheiroInput info){

   if(strcmp("Visitante",info.tipo) == 0){

   printf("ID: %d | ",info.id);
   printf("%s | ",info.tipo);
   printf("Entrada: %d | ", info.entrada);
   printf("Saida: %d | ",info.saida);
   printf("Serviço: %d\n",info.servico);

   }else{
   printf("ID: %d | ",info.id);
   printf("Acompanhantes: %d | ",info.acompanhantes);
   printf("Tipo: %s | ",info.tipo);
   printf("Entrada: %d | ", info.entrada);
   printf("Saida: %d | \n",info.saida);
   }
}

int validacaoVisitante(char dados[5][20]){

if(atoi(dados[0]) == 0  ){ //validação do ID
    return 0;
}

    //Validação da entrada
if(!isDigit(dados[2]) || atoi(dados[2])>24 || atoi(dados[2])<0){
     return 0;
}
    //Validação saida
if (!isDigit(dados[3]) || atoi(dados[3])>24 || atoi(dados[3])<=0){
     return 0;
}


    //validação do serviço
if(!isDigit(dados[4]) && dados[4] == 0){
     return 0;
}
return 1;

}


int isDigit(char *string){
char *p;
int firstDigit = 0; // A princípio, nenhum dígito foi encontrado.
int lastDigit = 0;  // A princípio, nenhum dígito foi encontrado.
int result = 1;     // A princípio, considera-se verdadeiro, que é digito.

p = string;

while (*p){
    if (*p >= '0' && *p <= '9'){
        p++;
        firstDigit = 1;
    }
    else if (*p == ' ' && !firstDigit){
        p++;
    }
    else if (*p == ' ' && firstDigit && !lastDigit){
        lastDigit = 1;
        p++;
    }
    else if (*p == ' ' && lastDigit){
        p++;
    }
    else{
        result = 0;
        break;
    }
}

return firstDigit && result;
}


void lerFicheiroInput(){
struct informacaoFicheiroInput informacao[20];
int tokenCount=0;
FILE* file;
file = fopen("input.txt","r");

if(file == NULL){
    printf("Não foi possivel abrir o arquivo.\n");
}

char line[100], *token, dados[5][20];
int info = 0;

while(fgets(line, sizeof line, file) != NULL){
    int count=0,i=0;
    token = strtok(line," ; ");

    while(token != NULL && count < 15){

        strcpy(dados[count++], token);
        token = strtok(NULL, " ; ");
        i++;
        tokenCount++;
    }

    // Mete os dados lidos da info-esima linha
    // em informacao.
    if(strcmp("Visitante", dados[1]) == 0 && validacaoVisitante(dados)==1){
       informacao[info].id = atoi(dados[0]);
       strcpy(informacao[info].tipo, dados[1]);
       informacao[info].entrada = atoi(dados[2]);
       informacao[info].saida = atoi(dados[3]);
       informacao[info].servico = atoi(dados[4]);
       info++;
    }else if (atoi(dados[0])!=0 &&(strcmp("Diretor",dados[2])==0 || 
strcmp("Funcionario",dados[2])==0)) {
       informacao[info].id = atoi(dados[0]);
       informacao[info].acompanhantes = atoi(dados[1]);
       strcpy(informacao[info].tipo, dados[2]);
       informacao[info].entrada = atoi(dados[3]);
       informacao[info].saida = atoi(dados[4]);
       info++;
   }
    count++;
}

fclose(file);
for(int j = 0; j< info; j++){
   toString(informacao[j]);
}


}


void main(){
setlocale(LC_ALL,"");
lerFicheiroInput();

}
  • Could you give an example of input ?

  • I have a file with lines of the genus 2 ; 12 ; Funcionaio ; 10 ; 5 E I am dividing them this way (" ; "), counting the spaces before and after ";" then wanted to do this check to know if for example in a parameter that should have an integer I have a string or a float, for example

  • failed to inform the language you are using.

  • is on the tag, on the bottom

  • Take out all the for (int i = 0; i < 20; i++) and leaves only the "stuffing" of for because you’re not iterating on dados, I mean, you’re not using the index i for nothing. Otherwise, put atoi(dados[4]) == 0, at last if of the function instead of dados[4] == 0

  • Oh yes it makes sense! And yes tbm I’ve noticed == ?

  • You have to use a structure that has all the information of all the lines. You have something like this?

  • 1

    Yes I have everything, I can update the code on top, but there are still some lines of code

Show 3 more comments

3 answers

1

You can use the function isdigit() of the standard library ctype.h. Look at that:

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

int isDigit( const char * str )
{
    if(!str) return 0;     /* Se string for NULL, retorna 0 */
    if(!(*str)) return 0;  /* Se string for VAZIA, retorna 0 */

    while( *str )
        if( !isdigit( *str++ ) )
            return 0;     

    return 1;
}

int main( void )
{
    printf( "%d\n", isDigit( "1234567890" ) );
    printf( "%d\n", isDigit( " 123" ) );
    printf( "%d\n", isDigit( "987 " ) );
    printf( "%d\n", isDigit( "1234aeiou" ) );
    printf( "%d\n", isDigit( "  ABC1234567 " ) );
    printf( "%d\n", isDigit( "" ) );
    printf( "%d\n", isDigit( NULL ) );
    return 0;
}

Exit:

1
0
0
0
0
0
0

In case you want to ignore the espaços em branco contained before and/or after the digits, you can combine the functions isdigit() and isblank():

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

int isDigit( const char * str )
{
    int ret = 0;

    if(!str) return 0;
    if(!(*str)) return 0;

    while( isblank( *str ) )
        str++;

    while( *str )
    {
        if( isblank( *str ) )
            return ret;

        if( !isdigit( *str ) )
            return 0;

        ret = 1;

        str++;
    }

    return ret;
}

int main( void )
{
    printf( "%d\n", isDigit( "1234567890" ) );
    printf( "%d\n", isDigit( " 123" ) );
    printf( "%d\n", isDigit( "987 " ) );
    printf( "%d\n", isDigit( " 567 " ) );
    printf( "%d\n", isDigit( "0 1 2 3 4 5 6 7 8 9 0" ) );
    printf( "%d\n", isDigit( " 0 1 2 3 4 5 6 7 8 9 0 " ) );
    printf( "%d\n", isDigit( "1234aeiou" ) );
    printf( "%d\n", isDigit( "  ABC1234567 " ) );
    printf( "%d\n", isDigit( "" ) );
    printf( "%d\n", isDigit( NULL ) );

    return 0;
}

Exit:

1
1
1
1
1
1
0
0
0
0
  • as I use atoi to pass from string to integer, the original isDigit function says that NULL is = to 0. which for my program unfortunately is not useful to me

  • The function atoi() does not detect errors and returns 0 every time it fails! If you pass a value NULL for atoi(), he behaves so undefined, likely to host a disastrous segmentation failure!

  • If your intention is to make the function isDigit() proposed in my reply returns something other than 0 if the entry is NULL, just change the line if(!str) return 0;. View comments in code.

  • isDigit("0 1 2 3 4 5"); would return 1

  • @Marcelouchimura: ops! Solved!

  • isDigit("987 "); does not return 1.

  • @Marcelouchimura: Ufff, now it’s solved!

Show 2 more comments

0


int isDigit(char *string)
{
    char *p;
    int firstDigit = 0; // A princípio, nenhum dígito foi encontrado.
    int lastDigit = 0;  // A princípio, nenhum dígito foi encontrado.
    int result = 1;     // A princípio, considera-se verdadeiro, que é digito.

    p = string;

    while (*p)
    {
        if (*p >= '0' && *p <= '9')
        {
            ++p;
            firstDigit = 1;
        }
        else if (*p == ' ' && !firstDigit)
        {
            ++p;
        }
        else if (*p == ' ' && firstDigit && !lastDigit)
        {
            lastDigit = 1;
            ++p;
        }
        else if (*p == ' ' && lastDigit)
        {
            ++p;
        }
        else
        {
            result = 0;
            break;
        }
    }

    return firstDigit && result;
}

Use:

for (i = 0; i < 20; i++) 
{
    if (!isDigit(dados[3][i]))
    {
        return 0;
    }
}
return 1;
  • Marcelo how would pass the string pointer data[3] for example?

  • 1

    It worked perfectly! If you find any error I ask for clarification, but it has been a great help in this project!

  • Marcelo for the visitor lines I made the following function: validationVisitant, I edited in the code above, now is no longer saving me any visitors, what I’m doing wrong?

  • To know if it is a visitor record, do not just compare dados[1] with " Visitante "?

  • Yes that part is already, but we have several validations to do, the following are considered invalid data: Lines with insufficient information. Lines with excess information. Lines with data of invalid types. Lines with persons whose representation is invalid. It is not known how many entries there are in the file. There can be no more than one entry per person. The visitor cannot visit a service whose employee has not yet entered. People, whether they are visitors or employees, with the number 5 and/or 10 cannot enter

  • Only need to validate if ID is equal or not

  • I commented on your question, check it out.

Show 2 more comments

0

#include <stdio.h>
#include <string.h>
int verifica(char *nome);

int main(int argc, char** argv)
{
  char nomes[4][100];
  int tam, resultado;
  for(int i = 0; i < 4; i++)
  {
    scanf("%s", nomes[i]);
  }
  for(int i = 0; i < 4; i++)
  {
     tam = strlen(nomes[i]);
     resultado = verifica(nomes[i]);
     if(resultado == tam) //se o tamanho for igual o ao que função retornar ele só contem numeros
     {
        printf("%s\n", nomes[i]);
     }
  }
   return 0;
}

int verifica(char *nome)
{
  int tam = strlen(nome), cont = 0;
  for(int i = 0; i < tam; i++)
  {
     if(nome[i] >= '0' && nome[i] <= '9') // se ele for numero, o contador e incrementado
     {
        cont++;
     }
  }
  return cont;
}

Browser other questions tagged

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