如何修复c中的字符串或指针?

时间:2014-04-12 14:56:57

标签: c pointers

我正在进行转换编程工作。我们必须将lbs转换为kgs,反之亦然,但是当我运行我的代码时,这是输出

100kgs = 220(空白)

在空白的地方,字母“lbs”不会出现。知道为什么???

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


void convert_weight(int weight1, char units1[], int* weight2, char units2[])
{

    int l = strcmp(units1, "lbs");
    int k = strcmp(units1, "kgs");


    if(l == 0) {

        *weight2 = weight1 /2.2;
        units2 = "kgs";
    }
    else {
        if(k == 0)
        {

        *weight2 = weight1 *2.2;
        units2 ="lbs";
    }
    }


}

int main() {
  char newline, another = 'y';
  int weight1, weight2;
  char units1[4], units2[4]; // length 4 because of '\0'
  while (another == 'y') {
    printf("Enter a weight and the units of the weight (lbs or kgs)\n");
    scanf("%d %s", &weight1, units1);
    convert_weight(weight1, units1, &weight2, units2);
    printf("%d %s = %d %s\nAnother (y or n)\n", weight1, units1, weight2, units2); 
    scanf("%c%c", &newline, &another)    ;
  }
  return 0;
}

2 个答案:

答案 0 :(得分:0)

您需要将单位字符串复制到unit2,而不是简单地将其分配到convert_weight

我无法记住这个功能,但我认为它是:

strncpy(unit2,"xxx",max);

其中max是您必须传递的新边界检查int,在调用代码中被视为sizeof(unit2),因此:

convert_weight(..., units2,sizeof(unit2));

答案 1 :(得分:0)

用作转换:

void convert_weight(int weight1, char units1[4], int *weight2, char units2[4])
{
  if (strcmp(units1, "lbs") == 0)
    {
      *weight2 = weight1 / 2.2;
      strcpy(units2, "kgs");
    }
  else if (strcmp(units1, "kgs") == 0)
    {
      *weight2 = weight1 * 2.2;
      strcpy(units2, "lbs");
    }
  else
    printf("Invalid units: %s\n", units1);
  units2[3] = 0; // '\0'                                                                                                                                                                                    
}