gpt4 book ai didi

CS50 (pset2) - 打印出首字母缩写的 C 程序中的行为不被理解

转载 作者:行者123 更新时间:2023-11-30 16:42:40 28 4
gpt4 key购买 nike

我之前有使用 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

最佳答案

get_initials函数的末尾,终止字符串:

...
initials[counter] = '\0';
return initials;

关于CS50 (pset2) - 打印出首字母缩写的 C 程序中的行为不被理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45735667/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com