我正在尝试将字符串指针数组传递给 C 中的函数 toupper()。
main() {
char *choice[1];
scanf("%s", choice);
printf("%s", toupper(&choice[0]));
}
我总是输入一个小写单词,例如“修改”来测试它。对此的不同变体,例如toupper(*choice[0])或toupper(*choice)它们的混合体,包括&,要么引发错误,要么返回相同的小写“修改”。有什么建议么?
从char具有一个元素的指针数组开始对我来说没有多大意义,因为它只会指向一个char字符串。如果你只想要一个字符串,为什么不声明一个数组呢?
原型toupper是这样的:
int toupper( int ch );
它不需要数组。
你可以这样尝试:
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[25];
int i = 0;
setbuf(stdout,NULL);
printf ("enter the name \n");
fgets (str,sizeof str-1, stdin);
printf ("the name entered in upper case is :\n");
while (str[i])
{
int c = str[i];
printf ("%c",toupper(c));
i++;
}
return 0;
}
注意-不要scanf用于带弦尝试fgets,它更好。
在你调用之前scanf,你需要为要存储的字符分配一些空间。你只分配一个指针,然后你甚至没有将它设置为指向任何东西。同样,toupper返回转换后的字符,不是字符串,所以传递给printfthrough%s也是错误的。
像这样的东西应该可以达到目的。
#include<stdio.h>
#include<ctype.h>
void StrToUpper(char *str)
{
while(*str != '\0')
{
*str = toupper(*str);
str++;
}
}
int main()
{
char *choice[1];
choice[1] = new char[10];
scanf("%s", choice[1]);
StrToUpper(choice[1]);
printf("%s", choice[1]);
return 0;
}
在程序中,您有指针数组。
所以:
toupper(choice[0][0]);toupper只接受一个字符值(0 到 255 之间),而不是指针或数组。