我之前有过使用Python的经验但是在C中是绝对的初学者。我正在研究 CS50x pset2缩写(不太舒服),其中一个简单的C程序应该接受由用户并打印出名称的首字母。
当我运行该程序时,它似乎适用于某些情况,但对于某些名称,它最后会附加一个错误的'B'字符。这是代码:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
string get_initials(string name, char initials[]);
int main(void)
{
// user input (full name)
printf("Please type your name: ");
string name = get_string();
// get the user name initials
char initials[10];
get_initials(name, initials); // in: full name; out: initials
printf("Initials: %s\n", initials);
}
string get_initials(string name, char initials[])
{
int counter = 0;
// Iterate over all characters
for (int i = 0, n = strlen(name); i < n; i++)
{
// in case the i-th char is ' ', appends next char to the initials array
if (name[i] == ' ')
{
initials[counter] = name[i+1];
counter++;
}
// appends the first char to the initials array
else if (i == 0)
{
initials[counter] = name[i];
counter++;
}
}
return initials;
}
这里有一些终端输出:
~/workspace/pset2/ $ ./initials
Please type your name: John Smith
Initials: JSB
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here
Initials: JSH
~/workspace/pset2/ $ ./initials
Please type your name: John
Initials: J
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here Again
Initials: JSHAB
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here Again Where
Initials: JSHAW
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here Again Where Here
Initials: JSHAWH
~/workspace/pset2/ $
我debugged for "John Smith"但仍然无法理解为什么它会附加 S \ 320 \ 330B 而不仅仅是 S 。
答案 0 :(得分:0)
在get_initials
函数结束时,终止字符串:
...
initials[counter] = '\0';
return initials;