我试图大写的关键字在1d数组通过使用函数toupper和额外的数组,但代码不能正常工作
我的代码是:#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main () {
char prog1[20], prog2[20];
char ch1, ch2;
int j = 0;
printf ("Enter a prog:");
gets(prog1);
printf ("Enter keywords:");
gets(prog2);
char upper = toupper(ch2);
while (prog1[j])
{
ch1 = prog1[j];
ch2 = prog2[j];
putchar(toupper(ch2));
j++;
}
return 0;
}
结果是:
Enter a prog:aaa bbb ccc
Enter keywords:bbb
BBB`?
目标是接收如下结果:
Enter a prog:aaa bbb ccc
Enter keywords:bbb
aaa BBB cccc
我非常感谢你的帮助
您需要初始化数组,因此在开始时清理它们:
char prog1 [20] = {' 0}, prog2 [20] = {' 0};
然后,你可以这样做:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main () {
char prog1[20] = {' '}, prog2[20] = {' '};
char ch1, ch2;
int i = 0, j = 0;
printf ("Enter a prog:");
gets(prog1);
printf ("Enter keywords:");
gets(prog2);
while (prog1[i])
{
j = 0;
while(prog2[j]){
if(prog1[i] == prog2[j]){
prog1[i] = toupper(prog2[j]);
}
j++;
}
putchar(prog1[i]);
i++;
}
return 0;
}