[英]How to fix strings or pointers in c?
我正在從事轉換編程任務。 我們必須將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;
}
您需要將單位字符串復制到unit2
而不僅僅是在convert_weight
分配它。
我不記得該函數,但我認為是:
strncpy(unit2,"xxx",max);
其中max是您還必須通過的新邊界檢查int
,在調用代碼中作為sizeof(unit2)
進行,因此:
convert_weight(..., units2,sizeof(unit2));
用作轉換:
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'
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.