【问题标题】:Detect input is character or number检测输入是字符还是数字
【发布时间】:2021-12-10 20:54:04
【问题描述】:

我正在编写一个程序来计算 2 个变量的总和。其中一个是从 1 到 10 的数字,另一个是字母表中的一个字母(大写),其值与其顺序相对应。输入只能是数字、字母或两者兼有。

例如:

输入

10  7     
C  8
E  D
9  F

输出

17
11
9
15

这是我的代码(这个问题应该发布在 codereview 上,但由于某种原因,我无法在 codereview 上正确格式化代码。请原谅我)。

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int main(){     
    char a[3], b[3];                        
    int m,n;
    //these variables hold the value of grade after converted  
                
    scanf("%s%s", a, b);

    if (a[1]!='\0')         
    {
      //this is because only number 10 has 2 digits    
        m=10;
    }
    else if (a[0]>=49 && a[0]<=57)
    {
        m=a[0]-48;      //in ascii table, 49 stands of 1 and 57 stands for 9
    }
    else
    {
        m=a[0]-64;      //in ascii table, 65 stands for 'A'
    }

    if (b[1]!='\0')              
    {
        n=10;
    }
    else if (b[0]>=49 && b[0]<=57)      
    {
        n=b[0]-48;
    }
    else         
    {
        n=b[0]-64;
    }

    printf("%d", m+n);
    return 0;
}

它有效,但我认为它有点复杂。所以想问问有没有办法优化检测。

以及如何处理大输入数。

任何帮助将不胜感激。

【问题讨论】:

  • 请将您的minimal reproducible example 复制粘贴(作为文本!)到问题本身。问题需要是独立的,并且主要部分应该在内容可以随时更改或消失的网站上。
  • 至于您的问题,the standard character classification functions 可能会有所帮助。
  • @Someprogrammerdude 谢谢,对我很有帮助
  • 在发布您的下一个问题之前,请了解如何在问题中正确格式化您的代码(我已经为您完成了)。这很简单,只需几分钟即可学会。
  • 我真的很感激。感谢您编辑我的帖子

标签: c optimization input


【解决方案1】:

您可以使用stroll 函数将字符串转换为long long。看起来干净多了,这个程序可以处理从-9223372036854775808到9223372036854775807作为输出。

#include <stdio.h>
#include <stdlib.h>

int main(void) {

  char string_num1[20], string_num2[20];
  scanf("%s%s", string_num1, string_num2);
  long long num1 = strtoll(string_num1, NULL, 10);
  long long num2 = strtoll(string_num2, NULL, 10);
  long long num3 = num1 + num2;

  printf("%lld", num3);

  return 0;
}

【讨论】:

  • scanf("%s%s", string_num1, string_num2); 是两个等待发生的缓冲区溢出。最好使用fgets() - 甚至更好的getline()(如果可用) - 然后您可以在返回的输入行上直接使用strtoll(),而不会陷入*scanf() 的泥潭。
  • 如果我在 'scanf' 中只使用 1 个 '%s' 可以吗,例如 'scanf("%s", string_num1);'然后 'scanf("%s", string_num2);'在下一行?
猜你喜欢
  • 2013-08-05
  • 2020-03-20
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 2017-02-27
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多