【问题标题】:A program that, given a string, a width, and an empty string for ouput, centers the string in the ouput area.一个程序,给定一个字符串、一个宽度和一个用于输出的空字符串,将字符串置于输出区域的中心。
【发布时间】:2015-07-03 19:38:00
【问题描述】:

功能是格式化成功返回​​1,发现错误返回0,如字符串长度大于宽度。我收到错误了吗?怎么了?我也不认为我说得对……

#include <stdio.h>

int main()
{
    int dummy, value = 0;

    formatString(value);

    scanf_s("%d",&dummy);
    return 0;
}

int formatString (char *in, 
              char *out, 
              int   width)
{
//Local Declarations
int spaces;
char *start;
char *walker;
int value;

spaces = (width – 1) – strlen(in);
if (spaces < 0)
{
    value = 0;
}
else
{
    start = out + (spaces / 2);
    for (walker = out; walker < start; walker++)
       *walker = ' ';
    strcpy (start, in);

    for (walker = out + strlen(out); 
         walker < out + width – 2; 
         walker++)
       *walker = ' ';
    *walker = ‘\0’;
}
    return value;
}

【问题讨论】:

  • 您的代码根本无法编译。 formatString 被错误地调用。你期待什么输出? -1,直到提供此信息。顺便说一句,不应该期望 SO 让你的代码编译。
  • 你不能单独使用 printf 吗?

标签: c string


【解决方案1】:

您的代码格式错误,无法辨认。你的作业解决方案如下所示:

int str_center(char *out, int width, char *in)
{
    int offset;

    // compute and check offset
    offset = (width - strlen(in)) / 2;
    if (offset < 0)
            return -1;

    // initialize output buffer
    memset(out, ' ', width - 1);
    out[width - 1] = '\0';

    // write result
    memcpy(out + offset, in, strlen(in));
    return 0;
}

首先,我们计算将输入字符串复制到输出字符串的偏移量。如果输入字符串严格大于输出字符串,这将是负数;在这种情况下,我们将退出并返回 -1。大多数开发人员使用零表示成功,非零表示失败,因为通常只有一种方法可以成功,而失败则有数千种方法。

然后,我们用空格初始化输出缓冲区,并用空终止符正确终止它。

最后,我们使用偏移量将输入字符串写入输出字符串,从所需位置开始。

请注意,我们不需要遍历任何字符串。 memset()memcpy() 将为我们做到这一点,而且效率可能更高。另请注意,我们只需要一个局部变量。您已经为这样一个微不足道的函数使用了四个局部变量。尽量减少局部变量的数量。如果您不能这样做,请拆分该功能。否则,两周后您将无法阅读自己的代码。而且从你努力的结果来看,你已经无法立即阅读了。

【讨论】:

  • 是不是更像这样? #include int main() { int dummy, value = 0; str_center(值); scanf_s("%d",&dummy);返回0; } int str_center(char *out, int width, char *in) { int offset; // 计算并检查偏移 offset = (width - strlen(in)) / 2;如果(偏移量
猜你喜欢
  • 1970-01-01
  • 2021-12-06
  • 2014-12-19
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 2013-05-07
相关资源
最近更新 更多