c - Sprintf 函数 + 顺序参数

标签 c string printf

<分区>

我有两个具有特定值的字符串 ta 和 tb,然后我在编写时使用函数 sprintf 将这两个字符串连接到变量 ta 中

sprintf(ta,"%s+%s",ta,tb);

我得到字符串 1+2。但我需要在 ta 中存储字符串 2+1 然后我尝试

sprintf(ta,"%s+%s",tb,ta);

但我得到了字符串 2+2+2+2+。我不明白为什么会这样,你能帮帮我吗?下面是完整代码

int main() {
    char ta[5];
    char tb[5];
    sprintf(ta,"%d",1);
    sprintf(tb,"%d",2);
    sprintf(ta,"%s+%s",ta,tb);
    //sprintf(ta,"%s+%s",tb,ta); uncomment for the second case
    printf("taid:%s",ta);
}

最佳答案

sprintf(ta,"%s+%s",ta,tb);
sprintf(ta,"%s+%s",tb,ta);

调用 sprintf 的两行都有未定义的行为。您正在尝试将 ta 复制到 ta 本身。

C11 §7.21.6.6 The sprintf function

The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.

关于c - Sprintf 函数 + 顺序参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29997645/

相关文章:

php - Sprintf 重复值

错误计算行数和运算符的 C 程序

c - 有没有办法优化这种数据的排序?

java - 如何确定字符串是否包含无效的编码字符

c - 我的程序被锁定了,似乎没有做它应该做的事情。我做错了什么?

haskell - Haskell printf 是如何工作的?

计算插入排序的步骤数

c - MSVC "error C2099: initializer is not a constant",其值由其他常量组成,仅在 C 上

SQL Server 存储过程连接字符串作为查询

c - 格式化字符串攻击,%_$d 和 %d 的区别