为什么我的程序输出奇怪的字符?
Why my program outputs weird characteres?
当我使用 3 个或更多名称时,我的程序会输出奇怪的字符。
当我使用 2 时完全没问题,当我使用大量空格时也很好。
但是当我尝试
考埃·罗德里戈·帕切科
输出是:
KRP]A
#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);
}
添加
initials[index] = 0;
在 printf
之前。您不会以零终止 char 数组。 C string 一些末尾为零的字符
当我使用 3 个或更多名称时,我的程序会输出奇怪的字符。
当我使用 2 时完全没问题,当我使用大量空格时也很好。
但是当我尝试 考埃·罗德里戈·帕切科 输出是: KRP]A
#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);
}
添加
initials[index] = 0;
在 printf
之前。您不会以零终止 char 数组。 C string 一些末尾为零的字符