【问题标题】:cs50 initials error with printed output打印输出的 cs50 首字母错误
【发布时间】:2017-03-30 23:19:48
【问题描述】:

我正在研究 Cs50 pset2 首字母。当我运行程序时,它会打印出名字的前 2 个字母和姓氏的第 2、4 和 6 个字母。我想知道我的增量是否错误?谢谢

这是我的代码..

#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
#include <string.h>

int main(void)
{
    // variables
    string urName;
    char init;
    int i;

    // get user input
    printf("Please state your full name:\n");

    do 
    {
        urName = get_string();
    }
    while (urName == NULL);

    printf("%c", toupper(urName[0]));

    for (i = 0, init = strlen(urName); i < init; i++)
    {
        if ((urName[i]) != '\0')
        { 
            printf("%c", toupper(urName[i+1]));
            i++;
        }
    }

    return 0;
}

这是示例输出..

Please state your full name:
den nguyen
DE GYN~/workspace/pset2/ $ 

【问题讨论】:

  • 您的增量错误。您有 两个 增量:一个在 for 循环头中,另一个在正文中。你只需要一个(第一个)..
  • 谢谢我删除了最后一个增量。非常感谢:)

标签: c cs50 edx


【解决方案1】:

正如 DYZ 提到的,您在 for 循环内的 2 个实例处增加计数器:

for (i = 0, init = strlen(urName); i < init; i++) // "i" is incremented here
{
    if ((urName[i]) != '\0')
    { 
        printf("%c", toupper(urName[i+1]));
        i++; // "i" is also incremented here
    }
}

通过增加 i 两次,编译器会在 for 循环的每次迭代中跳过一个字母。要修复它,您需要删除 for 循环内的 i++,以便只有 for 循环条件内的计数器增量工作:

for (i = 0, init = strlen(urName); i < init; i++) // "i" only needs to be incremented here
{
    if ((urName[i]) != '\0')
        printf("%c", toupper(urName[i+1]));
}

【讨论】:

  • 并且由于init = strlen(urName) 确保urName[i] 不会是空字节,因此内部测试是多余的(目前)。当代码尝试检测每个单词的首字母时,修改后的测试将变得相关——目前,它只是将所有内容都转换为大写。代码可以是:for (int i = 0; urName[i] != '\0'; i++) { putchar(toupper((unsigned char)urName[i])); }(它还修复了一些其他棘手的问题——如果您愿意,可以恢复 printf("%c", toupper(…));)。
  • 非常感谢您提供的所有反馈。我将使用您提供的条件并稍微清理我的代码。惊讶地看到 putchar(),我还没有学习这个函数,所以只要我的代码通过 check50 就会使用它。 xD
  • @omegaD 如果我的答案有效,请选中我的答案旁边的复选标记。当你这样做时它应该变成绿色。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
相关资源
最近更新 更多