为什么在字符串末尾添加 1?在这段代码中

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

我想创建一个文本文件,其名称由用户输入并带有 id 连接,正在创建该文件,但每次我 运行 时都会在扩展名的最后添加 1

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

我得到的输出是

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

预期输出是

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

在您的代码中

 char ex[4]=".txt";

不会为 null-terminator 保留 space,这会在您尝试将 ex 用作字符串时产生问题。由于没有 null-terminator,访问是通过分配的内存进行的,这导致 undefined behavior。将其更改为

 char ex[ ]=".txt";

自动确定保存字符串(包括空终止符)所需的数组大小,由字符串文字的 quote-delimited 初始化值初始化。