c++ - 默认 Switch 语句总是执行?

标签 c++ c

我有点困惑为什么我总是在这个简单的程序中得到默认情况。任何帮助将不胜感激...

#include <stdio.h>

char conversion(letter)
{
   switch(letter)
   {
       case 'A': 
            printf("a\n");
            break;

       case 'B': 
            printf("b\n");
            break;

       default: 
            printf("Not an upper case letter!\n");
            break;
   }         
   return letter;         
}


int main()
{
   char character;
   while ((character = getchar()) != '0')
         conversion(character);
}

最佳答案

根据您的描述,default case 由您输入的大写字母后面的换行符命中:空白字符,例如 '\n'由换行符产生的字符将由您的 switch() 处理。您可能想使用 isspace() 对空格进行排序(在 <ctype.h> 中声明):

if (!isspace((unsigned char)c)) {
    switch (c) {
        // ...
    }
}

关于c++ - 默认 Switch 语句总是执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20057763/

相关文章:

c - 添加 arp 条目 Linux

c++ - 超出索引 C/C++

c++ - 如何在 C++/OpenCV 中将 cv::Point 添加到数组或 vector ?

c++ - 如何使用 boost::future 重新抛出 std::exception_ptr 存储的原始异常?

c++ - 只允许枚举的子集作为返回值 - 或如何让编译器提醒我?在 C++ 中

c - c中的递归顺序

c - 使用某些浏览器的网络应用程序出现问题

c++ - boost LNK2019 错误

c - 错误: Invalid argument while trying to accept a connection from a client

c++ - 是否有任何库可以像 Open CV 访问摄像头一样访问 PC(Windows)麦克风?