当我使用3个或更多名字时,我的程序会输出奇怪的字符。
当我使用2完全没问题的时候,当我使用很多空格时也很好。
但是当我尝试的时候 kaue rodrigo pacheco 输出是: KRP]甲
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(void)
{
string name = get_string("What is your name?\n");
// initiate array that will contain all the initials
char initials[10];
// initials index
int index = 0;
// if first character is not a space then append to initials
if (name[0] != 32)
{
// if the character is not between A-Z
if (!(name[0] >= 'A' && name[0] <= 'Z'))
{
// transform it in uppercase
name[0] = name[0] - 32;
}
// append the character into initials array
initials[index] = name[0];
// keep track on how many were done
index++;
}
// iterate through the user input
for (int i = 1; i < strlen(name); i++)
{
if ((name[i] != 32) && (name[i - 1] == 32))
{
// if the character after the blankspace is not between A-Z
if (!(name[i] >= 'A' && name[i] <= 'Z'))
{
// transform it in uppercase
name[i] = name[i] - 32;
}
// append the character into initials array
initials[index] = name[i];
// keep track on how many were done
index++;
}
}
// end result, prints all initials uppercase
printf("%s\n", initials);
}
答案 0 :(得分:0)
添加
在initials[index] = 0;
之前 printf
。您不会使用零终止char数组。 C字符串中有多个字符,末尾为零