c - 为什么这会给出垃圾字符?

标签 c

我是 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/

相关文章:

组合公式 "n!/((n-k)!*k!)"不起作用

c - C中的空终止字符串

c - 从字符串中获取字符后的数字?

c - 将 csv 文件的输入解析为 char 数组

c - NASM ORG 指令有 GCC 版本吗?

c - 如何在 C 语言中使用 printf,我的代码应该打印出什么?

c - 如何根据操作数的类型决定结果的类型?

c - 这是 "inverting"一个字节的正确方法吗? (按位非)

c - 在运行时初始化全局二维 C 整数数组

c - 循环缓冲区突发丢失最后一个字节