我是 Visual Studio 的初学者。通过这段代码,我想将字符串中单词的第一个字母更改为大写字母,然后打印它们(仅大写)。这可以做到,但也会给出垃圾字符。这是代码。请帮助我。
# include <stdio.h>
# include <string.h>
char ToUpper(char input){
char output;
output = input - ('a'-'A');
return output;
}
void main (viod){
char name[40],name2[10] ;
int length,i,j,a,b;
scanf("%[^\n]s",&name);
printf("original input:%s\n",name);
length = strlen(name);
if(name[0]!=' '){
name2[0]=ToUpper(name[0]);
a=1;b=1;
}
else{
a=1; b=0 ;
}
for(i=a,j=b;i<=length;i++){
if(name[i]!=' '){
if(name[i-1]==' '){
name2[j]=ToUpper(name[i]);
j++;
}
}
}
printf("%s",name2);
getch();
}
最佳答案
#include<stdio.h>
#include<string.h>
char ToUpper(char input){
return toupper(input); // using inbuilt function
}
void main() {
char name[40]; // no need to create name2 array
int i;
scanf("%39[^\n]S", name); // you can use gets(name);
printf("The original input:%s\n", name);
for(i=0; i < strlen(name); i++) {
if (i == 0 || name[i-1] == ' ' && name[i] >= 'a' && name[i] <= 'z')
name[i] = ToUpper(name[i]); // or direct toupper(name[i]);
}
printf("%s", name); // you can use puts(name);
getch();
}
关于c - 为什么这会给出垃圾字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45253261/