Converting int to string

0

I made a program that simulates a login and when I convert the password that is in int to a string using sprintf it's from the failed segmentation, I tried to use the itoa but it's the error definition

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

int main()
{
   char login[6]={0};

   int passwd;
   char senha[6]={0};

   char logins[6]="Teste";
   char senhas[6]="12345";

  do{
     printf("\n\tDigite o Login: ");
     scanf("%s",login);

     if((strcmp(login, logins) == 0))break;
     else
     printf("\tUsuario: %s Inválido..!!\n", login);

     }while((strcmp(login, logins) != 0));

  do{
     printf("\n\tDigite sua senha: ");
     scanf("%d",passwd);

     sprintf(senha,"%s",passwd);

     if((strcmp(senha, senhas) == 0))
     printf("\n\tUsuario e Senha Válidos\n\tAcesso autorizado..!!!\n\n");
       else
     printf("\tSenha: %s Inválida..!!\n", senha);

    }while((strcmp(senha, senhas) != 0));

   return 0;
}
    
asked by anonymous 04.12.2017 / 20:35

1 answer

1
 printf(senha,"%s",passwd);

The "% s" should only be used if passwd were an array of characters (char []) as an integer use "% d"

However use the snprintf function, it avoids segmentation fault, that is the size of your array, given the size of your array, the function will never write more than allowed.

snprintf(senha, 6, "%d", passwd);

ITOA (Since no solution above worked)

Since your compiler lib does not have the function to convert int to char *, let's create one !!!:

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

char *  itoa ( int value, char * str )
{
    char temp;
    int i =0;
    while (value > 0) {
        int digito = value % 10;

        str[i] = digito + '0';
        value /= 10;
        i++;

    }
   i = 0;
   int j = strlen(str) - 1;

   while (i < j) {
      temp = str[i];
      str[i] = str[j];
      str[j] = temp;
      i++;
      j--;
   }
    return str;


}

int main()
{
   char login[6]={0};

   int passwd;
   char senha[6]={0};

   char logins[6]="Teste";
   char senhas[6]="12345";



  do{
     printf("\n\tDigite o Login: ");
     scanf("%s",login);

     if((strcmp(login, logins) == 0))break;
     else
     printf("\tUsuario: %s Inválido..!!\n", login);

     }while((strcmp(login, logins) != 0));

  do{
     printf("\n\tDigite sua senha: ");
     scanf("%d",&passwd);

     //sprintf(senha,"%s",passwd);
     //snprintf(senha, 6, "%d", passwd);
      itoa(passwd,senha);

     if((strcmp(senha, senhas) == 0))
     printf("\n\tUsuario e Senha Válidos\n\tAcesso autorizado..!!!\n\n");
       else
     printf("\tSenha: %s Inválida..!!\n", senha);

    }while((strcmp(senha, senhas) != 0));

   return 0;
}

Tested and working. In the scanf you have to pass the variable by reference thus:

scanf("%d",&passwd);

sample of the execution of the above code online link

    
06.12.2017 / 20:51