不完全打印的字符串



注意:这是作业,我只是想知道为什么我得到混乱的打印,而不是完成的程序。

#include    <stdio.h>
char    get_band( int band_number, char band_color[] );
void    get_resistance( int resist, int power );
int main()
{
    int     resist;
    int     power;
    get_resistance(resist, power );
}
void get_resistance( int resist, int power )
{
    int     band_number;
    char    band_color[3];
    char    color[3];

    get_band( band_number, band_color );
    printf("%s", band_color);
}
char get_band( int band_number, char band_color[] )
{
    int     x;
    x=0;
    while (x < 3)
    {
        printf("Which band would you like to select? (1-3)nDo not select one you have selected prior!t");
        scanf("%d", &band_number);
        if (band_number = 1)
        {
            printf("What color would you like to assign here?t");
            scanf("%s", &band_color[0]);
            x++;
        }
        else if (band_number = 2)
        {
            printf("What color would you like to assign here?t");
            scanf("%s", &band_color[1]);
            x++;
        }
        else if (band_number = 3)
        {
            printf("What color would you like to assign here?t");
            scanf("%s", &band_color[2]);
            x++;
        }
    }
    return (*band_color);
}

所以当我运行它时,我没有得到错误或警告,但我得到的是我输入的最后一个颜色。例如,我按顺序输入绿色、蓝色、黄色。我会把黄色印回去。不管我使用什么顺序的数字,我总是返回最后输入的颜色。

您的代码有两个主要问题:

:

if (band_number = 1) {
  ...
}

=是赋值运算符,==是等于运算符。由于band_number = 1总是求值为1,因此总是采取分支。

第二:

char    band_color[3];

,然后:

scanf("%s", &band_color[0]);

您没有声明足够的空间,并且您践踏了之前的值。此外,如果你想静态地分配字符串数组,你需要做的事情更像以下:

void get_resistance( int resist, int power )
{
  int     band_number;
  char    band_color[3][20];

  get_band( band_number, band_color );
  printf("%sn", band_color[0]);
  printf("%sn", band_color[1]);
  printf("%sn", band_color[2]);
}
void get_band( int band_number, char band_color[][20] )
{
  int     x;
  x=0;
  while (x < 3)
    {
      printf("Which band would you like to select? (1-3)nDo not select one you have selected prior!t");
      scanf("%d", &band_number);
      printf("What color would you like to assign here?t");
      scanf("%s", band_color[band_number - 1]);
      x++;
    }
}
我已经大大简化了你的代码逻辑,因为你有很多重复。关键的一点是char band_color[3][20]将声明足够的空间容纳3个长度为20个字符的字符串(包括终止字符)。get_band的函数原型已经改变,以适应新的band_color类型。

通过观察用户输入的数字总是比数组索引大1,代码简化实际上删除了if语句。然后,您可以用该数字减去1来索引数组,即band_color[band_number - 1]

注意,如果在提示时键入两个长度的字符串,这很容易导致缓冲区溢出。这不是高质量的代码,只是试图证明你的错误

如果发现这个链接对获取用户输入很有帮助。

也是一个很好的链接,说明为什么使用scanf对用户输入不利。

你的程序有一些问题。有很多不必要的冗余变量传递。可以将band_color声明为全局变量,也可以在get_band函数中声明。band_number也是一样。没有理由在get_resistance中声明它,只是为了将它传递给get_band。只需在get_band中声明它,因为这是唯一使用它的地方。然后,您可以返回一个指向band_color数组的指针,以用于打印。在get_band中的if语句中,您错误地编写了求值器。你在该用=的地方用了==.

if (band_number == 1)

这会导致您的代码允许进入第一个if并且只将变量赋值给[0]数组。你的数组只需要是[2],因为这给了你3个条目。此外,您还需要用第二组大括号声明数组中字符串的长度。

char band_color[2][10];

最新更新