cstringitoa

why 1 is getting added at the end of string? in this code


I want to create a text file with the name entered by the user and with id concatinated,The file is getting created but the 1 is getting added at the last of extension every time i run it

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int main(int argc, char const *argv[])
{
    char name[50];int id=1;
    printf("Enter your name:\n");
    scanf("%s",name);
    char ids[10];
    itoa(id, ids, 10);
    strcat(name,ids);
    printf("%s\n",name );
    char ex[4]=".txt";
    printf("%s\n",ex );
    strcat(name,ex);
    printf("Filename :%s\n",name);
    return 0;
}

the output i am getting is

Enter your name:
file
file1
.txt1    // i don't know why this 1 is getting added
Filename :file1.txt1

expected output is

Enter your name:
file
file1
.txt
Filename :file1.txt

Solution

  • In your code

     char ex[4]=".txt";
    

    does not leave space for a null-terminator, which creates a problem when you try to use ex as a string. As there's no null-terminator, the access is made past the allocated memory, which leads to undefined behavior. Change this to

     char ex[ ]=".txt";
    

    which automatically determines the size of the array needed to hold the string (including the null terminator), initialized by the quote-delimited initializer value of the string literal.