我正在尝试创建一个程序,要求用户首先输入他们想要从小写转换为大写的值的数量。然后 for 循环将每个值分配到一个数组中。然后,该数组通过另一个 for 循环,使用 LowerToUpper 函数将值转换为大写。
当我运行该程序时,它将接收值,然后开始在命令窗口中将它们加倍,并在您完成输入值时停止,而不是打印结果。您能解释一下原因吗?预先感谢您
#include<stdio.h>
#include <string.h>
#include <ctype.h>
void LowerToUpper(char* array)
{
toupper(*array);
}
int main(void)
{
int i, amount;
printf("How many values?\n");
scanf("%d", &amount);
char *d;
char array1 [amount];
printf("Please enter the values\n");
for(i=0; i<amount; i++)
{
scanf("%c", &array1[i]);
}
for(i=0; i<amount; i++)
{
d=&array1[i];
LowerToUpper(d);
scanf("%c", &array1[i]);
printf("%c", array1[i]);
}
return 0;
}
最佳答案
您没有正确使用toupper()
。如果成功,函数返回转换后的值。您需要利用返回值。提供的参数未更改。
也就是说,程序结构不必要地复杂。你可以像这样简化它
for(i=0; i<amount; i++)
{
int result = toupper (array1[i]);
if (result != array1[i]) printf("%c", result); //just checkin', if converted
}
也就是说,您还有许多其他目前没有看到的问题,例如
scanf("%c", &array1[i]);
令您惊讶的是,这只会要求您提供一半的输入数量。为什么?您忘记忽略 RETURN 键输入的换行符。
然后,您没有检查 scanf("%d", &amount);
调用是否成功。如果扫描失败,您最终会得到 undefined behavior .
最后一个 for
循环中的第二个 scanf()
可能是您不想要的,它充其量是无用的。
关于c - 无法使用 toupper 将值从小写转换为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46234322/