0

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
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Aviroxi
  • 115
  • 1
  • 9

1 Answers1

3

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • i am unable to accept the answer it is showing you can accept answer after 12 min after 12 min i will accept your answer, thank you so much – Aviroxi Nov 05 '20 at 13:03