strcat str

问题描述 投票:0回答:3

这是我的代码

#include <stdio.h>
#include <string.h>

int mypow(int s, int times); //only a pow function return a int

int main(void)
{
  int a;
  char str[80];
  char result[80];
  int cur;
  int input = 152;
  int len = 3;
  sprintf(str, "152 = ");
  strcat(result, str);
  for (a = 0; a < len; a++)
  {
    cur = input % 10;
    input = input / 10;
    if (a == 0)
    {
      sprintf(str, "%i", cur);
      strcat(result, str);
      sprintf(str, " + ");
      strcat(result, str);
    }
    else if (a < len - 1)
    {
      sprintf(str, "%i*%i", cur, mypow(10, a));
      strcat(result, str);
      sprintf(str, " + ");
      strcat(result, str);
    }
    else
    {
      sprintf(str, "%i*%i", cur, mypow(10, a));
      strcat(result, str);
    }
  }
  puts(result);
  return 0;
}

我希望将下面的代码放到终端上

152 = 2 + 5*10 + 1*100

但我得到了这样可能的结果

E:\c>e:\c\hello.exe
X152 = 2 + 5*10 + 1*100

E:\c>e:\c\hello.exe
X?52 = 2 + 5*10 + 1*100

E:\c>e:\c\hello.exe
X?52 = 2 + 5*10 + 1*100

这个过程中发生了什么

c
3个回答
5
投票

你使用

sprintf(str, "152 = ");
strcat(result, str);

在初始化之前

result

因为

result
没有初始化,所以它的内容是不确定(看它是随机的还是垃圾)。

要使用

strcat
,两个字符串都必须是正确的以 null 结尾的字符串。

最简单的解决方案是使用

strcpy
将文字字符串直接复制到
result
:

strcpy(result, "152 = ");

或者可能跳过它并在定义时初始化

result

char result[80] = "152 = ";

1
投票

问题就在一线

strcat(result, str);

您将

str
连接到
result
,但没有初始化
result
变量,因此开始时存在一些垃圾。

你应该使用

strcpy()

strcpy(result, str);

1
投票

问题:

char result[100];
未初始化。
它不能在
strcat( result, ...
中可靠地用作 C 字符串。
strcat()
首先扫描预期的
'\0'
(以找到开始连接的位置。)

补救措施:
使用

strcpy( result, ...
作为构建字符串的第一个操作。


建议在尝试新知识熟悉更多知识之间平衡你的时间和精力。您的代码显示了为实现您的目标所做的勇敢努力。向你致敬!

下面显示的是您可能希望通过学习该语言提供的可用设施和(经证明有效的)C 标准库函数来实现的目标的一个示例。 (

printf()
可以成为强大的力量!)此代码代表了(就像您一样)多年的阅读和实验。此处介绍是为了鼓励您不断发现新事物。

#include <stdio.h>

// write experimental code in functions from the beginning.
// leave main() uncluttered.
char *expand( char *buf, int val ) {
    char *at = buf; // travelling pointer

    at += sprintf( at, "%d", val ); // initialise buffer with digits
    int idgt = at - buf - 1; // calculate index of last ASCII digit

    char *sym = " = "; // "connector" symbol to print

    for( int i = 0, x10 = 1; buf[i] != ' '; i++, x10 *= 10 ) {
        // append symbol, this digit, char '*', and "power of 10" multiplier
        // return count of output characters to advance buffer pointer
        at += sprintf( at, "%s%c*%d", sym, buf[idgt--], x10 );
        sym = " + "; // use this symbol from now on.
    }

    return buf;
}

int main( void ) {
    char buf[ 256 ]; // be generous with temp buffer size

    puts( expand( buf,   152 ) ); // test
    puts( expand( buf, 65536 ) ); // and test again

    return 0;
}

输出:

152 = 2*1 + 5*10 + 1*100
65536 = 6*1 + 3*10 + 5*100 + 5*1000 + 6*10000

变化:

  • 按递减顺序打印扩展。
  • 使用“*10^n”符号打印。
  • 它对于负数有效吗? (可能有 2 种输出风格。)
© www.soinside.com 2019 - 2024. All rights reserved.