问题描述
我想创建一个文本文件,其名称由用户输入,且ID带有隐含的名称,正在创建该文件,但是每次我运行扩展名的最后一个都添加了该文件
#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";
不会为空终止符留出空间,这会在您尝试将ex
用作字符串时产生问题。由于没有空终止符,因此访问是通过分配的内存进行的,这将导致undefined behavior。更改为
char ex[ ]=".txt";
它会自动确定保存字符串所需的数组大小(包括空终止符),并由字符串文字的用引号分隔的初始化值进行初始化。