【问题标题】:why 1 is getting added at the end of string? in this code [duplicate]为什么要在字符串末尾添加 1?在这段代码中[重复]
【发布时间】:2021-02-18 04:32:55
【问题描述】:

我想创建一个文本文件,其名称由用户输入并连接 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

【问题讨论】:

    标签: c string itoa


    【解决方案1】:

    在你的代码中

     char ex[4]=".txt";
    

    不会为空终止符留出空间,这会在您尝试将ex 用作字符串时产生问题。由于没有空终止符,因此访问是通过分配的内存进行的,这导致undefined behavior。将其更改为

     char ex[ ]=".txt";
    

    它自动确定保存字符串所需的数组大小(包括空终止符),由字符串文字的引号分隔的初始化值初始化。

    【讨论】:

    • 我无法接受它显示的答案,您可以在 12 分钟后接受答案 12 分钟后我会接受您的答案,非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    相关资源
    最近更新 更多