首页 > 解决方案 > 代码在为彼此切换字母时出错

问题描述

当我尝试进行简单的字符交换时,代码出现故障。下面列出了代码以及错误的屏幕截图。

#include <stdio.h>

int main()
{
    char Ghost[12] = "SimonGhost";
    int ghostdeathdate = 5;
    char Price;
    int Soap;
    while (ghostdeathdate > 0)
    {
        scanf("%c %d", &Price, &Soap);
        Ghost[Soap] = Price;
        printf("%s\n", Ghost);
        --ghostdeathdate;
    }
    return ghostdeathdate;
}

标签: arrayscstringchar

解决方案


问题是每次调用时缓冲区中留下的新行scanf,您需要使用空格来消耗每个新行:

scanf("%c %d", &Price, &Soap);

应该

scanf(" %c %d", &Price, &Soap); // Notice a space before %c

推荐阅读