【问题标题】:C++ Looping and scanf validate alphabet, capital alphabet and numbersC++ 循环和 scanf 验证字母、大写字母和数字
【发布时间】:2016-12-20 18:18:18
【问题描述】:

我的代码有问题,在我编译并运行代码后出现,它会输出两次并且输出错误。

我的任务是重复输入数字/字母/大写并相应地输出结果。至于while循环,我相信我必须把while(1)

#include <stdio.h>
int main()
{
    char c;
    int num;

    printf("\nEnter a character: ");
    scanf("%c", &c);

    if ((c >= 'a' && c <= 'z')) 
        printf("%c\nIt is an alphabet.", c);

    if ((c >= 'A' && c <= 'Z'))
        printf("%c\n It is a capital alphabet.", c);

    if (c <= '1' ||c >= '1') 
        printf("\nIt is a numeric");

    else 
        printf("error");

 return 0;
}

【问题讨论】:

  • 应该有一个else if 链...但它不存在...
  • if (c &lt;= '1' ||c &gt;= '1') 是错误的。 – 您是否尝试调试代码?
  • 请确保您确切知道您正在学习什么语言。您的代码类似于 C。C 和 C++ 是非常不同的语言。
  • 你真的不应该写这样的比较来确定一个角色的类别。您有 std::islowerstd::isupperstd::isdigit 用于此目的。例如,如果您的系统是 EBCDIC,那么您对小写的比较将失败。让标准函数确定角色类别——它知道您可能不知道的所有这些细节。

标签: c++ c while-loop scanf


【解决方案1】:

你需要这样的工作:

#include <stdio.h>

int main()
{
 char c;
int num, int general=0;

printf("\nEnter a character: ");
scanf("%c", &c);



if ((c >= 'a' && c <= 'z')) {
    printf("%c\nIt is an alphabet.", c);
    general++;
  }


if ((c >= 'A' && c <= 'Z')){
    printf("%c\n It is a capital alphabet.", c);
    general++;
  }

if (c <= '1' ||c >= '1') {
    printf("\nIt is a numeric");
    general++;
  }


if (general==0)
    printf("error");

 return 0;
}

或者你可以在“catch and switch”中使用。

【讨论】:

    【解决方案2】:

    需要进行三处更改。

    首先使用else if

    其次要测试数字使用c &gt;= '0' &amp;&amp; c &lt;= '9'

    最后但并非最不重要的一点是:使用getchar() 作为循环的最后一条语句来吃掉缓冲区中的\n 字符,而不是被scanf 占用

    【讨论】:

    • 没错。 @LogicStuff。在那之前我就想到了使用 ASCII 值。
    猜你喜欢
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2013-02-04
    • 2014-12-09
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多