【问题标题】:(C programming) while true loop with switch case, always run in default case(C 编程)while true 循环与 switch case,总是在默认情况下运行
【发布时间】:2021-10-01 03:08:27
【问题描述】:

我是 C 编程的新手。 我正在练习通过无限循环读取用户输入,并检查输入是元音还是常量。 我用一个开关来检查它,但是当我执行我的代码时,总是执行默认情况,我被卡住了。

如果有人能给我一些建议,将不胜感激,谢谢!

#include <stdio.h>

void checkIfVowel(char *c);

int main()
{
    char c;
    while (1)
    {
        printf("Please enter a character: ");
        scanf("%c", &c);
        checkIfVowel(&c);
    }
    return 0;
}

void checkIfVowel(char *c)
{
    switch (*c)
    {

    case 'A':
        printf("%c is a vowel! \n", *c);
        break;
    case 'E':
        printf("%c is a vowel! \n", *c);
        break;
    case 'I':
        printf("%c is a vowel! \n", *c);
        break;
    case 'O':
        printf("%c is a vowel! \n", *c);
        break;
    case 'U':
        printf("%c is a vowel! \n", *c);
        break;
    case 'a':
        printf("%c is a vowel! \n", *c);
        break;
    case 'e':
        printf("%c is a vowel! \n", *c);
        break;
    case 'i':
        printf("%c is a vowel! \n", *c);
        break;
    case 'o':
        printf("%c is a vowel! \n", *c);
        break;
    case 'u':
        printf("%c is a vowel! \n", *c);
        break;
    default:
        printf("%c is a constant! \n", *c);
        break;
    }
}

【问题讨论】:

  • 换行符也是一个字符,将由scanf("%c",..)返回。
  • 谢谢! @interjay 我该如何修改它?
  • 您不需要将指针传递给checkIfVowel。而且您不需要函数中的所有printf 调用...case 'A': case 'E': ... case 'U': printf(...); break; 也可以。
  • 我还建议您了解touppertolower。可以省略一半的案例。

标签: c while-loop switch-statement


【解决方案1】:

简单的改变就足以消除错误。但是你可以简单地做到这一点,即使在 1 行代码中使用带有逻辑条件的 if-else 语句而不是这个 switch case。!就试一试吧!我只附加错误删除的代码

#include <stdio.h>

void checkIfVowel(char *c);

int main()
{
    char c;
    while (1)
    {
        printf("Please enter a character: ");
        scanf("%c", &c);
        checkIfVowel(c);
    }
    return 0;
}

void checkIfVowel(char* c)
{
    switch ((char) c)
    {

    case 'A':
        printf("%c is a vowel! \n", c);
        break;
    }
    
}

 

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多