我正在尝试修改一个字符串,然后在 C 中返回它。但是代码不能很好地工作。当我在 main
中运行该函数时,wordOfNum
返回一个空字符串
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
char *wordOfNum(int number, int spec) {
char *word = malloc(strlen("Example") + 1);
if (spec == 0) {
switch (number) {
case 1:
strcpy(word, "one");
break;
case 2:
strcpy(word, "two");
break;
case 3:
strcpy(word, "three");
break;
case 4:
strcpy(word, "four");
break;
case 5:
strcpy(word, "five");
break;
case 6:
strcpy(word, "six");
break;
case 7:
strcpy(word, "seven");
break;
case 8:
strcpy(word, "eight");
break;
case 9:
strcpy(word, "nine");
break;
}
}
else if (spec == 1) {
switch (number) {
// case 1: return "one";
case 2:
strcpy(word, "twenty");
break;
case 3:
strcpy(word, "thirty");
break;
case 4:
strcpy(word, "fourty");
break;
case 5:
strcpy(word, "fifty");
break;
case 6:
strcpy(word, "sixty");
break;
case 7:
strcpy(word, "seventy");
break;
case 8:
strcpy(word, "eightty");
break;
case 9:
strcpy(word, "ninety");
break;
}
}
return word;
}
void exercise1() {
char num[4];
printf("This is exercise 1: \n");
printf("Enter a 4 digit number: ");
scanf("%[^\n]%*c", num);
printf("%s thoundsand %s hundred %s %s", wordOfNum(num[0], 0), wordOfNum(num[1], 0), wordOfNum(num[2], 1), wordOfNum(num[3], 0));
}
int main() {
exercise1();
return 0;
}
我认为问题在于范围界定。在 wordOfNum
处,我使用嵌套在 if
中的 switch
,因此 word
不会按预期更改。当我 strcpy
word
1 级时,这意味着仅在单个 if 中,word
可以更改
最佳答案
所以问题是你正在混合 int
和 char
s,你作为参数传递的实际上是一个 char
,解决此问题的一个简单方法是将 char
转换为您传递为 number
int
的参数。如果您想避免这种转换,您可以更改 switch
es 来自 case 1:...
至case '1':...
,当然是所有这些。
您还应该使用char num[5];
空终止符的空间,以及 scanf("%4[^\n]%*c", num);
以避免缓冲区溢出。
仍然需要验证输入的值是否确实是 4 位数字字符串,否则结果将不是预期的。
char *wordOfNum(int number, int spec) { //or char number
//...
int num = number - '0'; //convert char to int
if(num > 9 || num < 0){ //check if input is a 4 digit number
puts("The input must be a 4 digit number!");
exit(EXIT_FAILURE); // or handle it as you see fit
}
if (spec == 0) {
switch (num)
{
//...
}
}
else if (spec == 1) {
switch (num)
{
//...
}
}
return word;
}
正如@DeiDei所述在评论部分,你可以避免 malloc
只需使用 word = "one";
等等,而不是 strcpy(word,"one");
并将返回类型更改为 const char*
以避免尝试编辑字符串文字。
关于c - 如何修改字符串并返回它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61733708/