检查字符数组是否包含纯数字或纯字符

时间:2014-02-21 12:25:38

标签: c

如果输入包含除数字之外的任何内容,我正在尝试让我的代码向我发送错误消息。收到的输入如下

int main(int argc, char *argv[]) {

它接收的输入如下(我在终端期间通过执行传递值)

//multiply.exe 12 4     <-- Ok
//multiply.exe a12 4    <-- error
//multiply.exe 1 b      <-- error
//multiply.exe 12a 3    <-- Ok, but this should give me an error

以下是完整代码(减去标题)

int main(int argc, char *argv[]) {
    if(argc == 1) {
        printf("\n>> Please pass arguments!\n\n");
        return 1; //Terminate with errors
    } else if(argc > 3) {
        printf("\n>> Too many inputs!");
        printf("\n>> Please limit them to only two numbers!\n\n");
        return 1; //Terminate with errors
    } else {
        if(isdigit(*argv[1]) && isdigit(*argv[2])) { //Check if both inputs are numbers
            /*NOTE: isdigit() ignores none-number characters placed after a leading digit
             *i.e: '123edf' valid, 'edf123' not valid
             */
            int a = atoi(argv[1]);
            int b = atoi(argv[2]);
           /*NOTE: atoi() converts none-integer characters to zeros 
            *(including any numbers after/in-between)
            *but, doesn't pad the number with them.
            *i.e: '123edf' = 123, 'edf123' = 123
            */
            printf("\n>> %d x %d = %d\n\n", a, b, a*b); //Display multiplication of input
       } else { //Display invalid input
            printf("\n>> INVALID INPUT: %s\n\n", (isdigit(*argv[1])) ? argv[2] : argv[1]);
            return 1; //Terminate with errors
       }
   }

    return 0; //Terminate successfully
}

2 个答案:

答案 0 :(得分:1)

isdigit只检查一个字符。

你需要创建一个类似于:

的函数
bool check_string(const char* string) {
  const int string_len = strlen(string);
  for(int i = 0; i < string_len; ++i) {
    if(!isdigit(string[i])) 
      return false;
  }
  return true;
}

答案 1 :(得分:0)

通过strtol检查

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

bool isInt(/* in */ char *string,/* out */ int *num){
    char *endp;
    long n;
    n = strtol(string, &endp, 0);
    if(!*endp && !errno && INT_MIN <= n && n <= INT_MAX) {
        *num = (int)n;
        return true;
    }
    return false;
}


int main(int argc, char *argv[]) {
    //omit
    int a, b;
    bool ba, bb;
    ba = isInt(argv[1], &a);
    bb = isInt(argv[2], &b);
    if(ba && bb){
        printf("\n>> %d x %d = %d\n\n", a, b, a*b);
        return EXIT_SUCCESS;
    }
    if(!ba)
        printf("\n>> INVALID INPUT: %s\n\n", argv[1]);
    if(!bb)
        printf("\n>> INVALID INPUT: %s\n\n", argv[2]);
    return EXIT_FAILURE;
}