首页 > 解决方案 > 检测输入是字符还是数字

问题描述

我正在编写一个程序来计算 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;
}

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

以及如何处理大输入数。

任何帮助,将不胜感激。

标签: coptimizationinput

解决方案


您可以使用stroll函数将字符串转换为long long. 它看起来更干净,并且该程序可以将 from 处理-92233720368547758089223372036854775807输出。

#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;
}

推荐阅读