2014-02-21 4 views
0

입력에 숫자 만 있으면 오류 메시지가 표시됩니다.문자 배열에 순전히 숫자 또는 순전히 문자가 포함되어 있는지 확인하십시오.

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 

전체 코드 (마이너스 헤더)

이다 (I 단말 동안 실행을 통해 값을 전달할) 따르고
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 
} 
+1

당신은 http://en.cppreference.com/ ([strtol''] 사용할 수 있습니다 w/c/string/byte/strtol)이 매우 쉽습니다. 문자열을 숫자 *로 변환하고 *는 숫자가 아닌 문자열을 검사하는 데 도움이됩니다. 그것은 심지어 당신이 지금 문제가있는 음수를 처리 할 것입니다. –

+0

@ user2337345 - 우르 코드는 괜찮습니다. 여기서 당신의 문제는 무엇입니까? 당신은 무엇을 기대하고 있습니까? – arunb2w

+0

@Joachim Pileborg 방금 음수로 코드를 테스트 했으므로 처리 할 수있었습니다. 그러나 '123edf 12'와 같은 입력은 * argv []를 2D 문자 배열로 변환한다는 것이 나에게 발생했습니다. 지금 이것을 확인하려고합니다. – user2337345

답변

1

isdigit은 단일 문자를 검사합니다.

당신은 같은 것을 수행하는 함수를 만들 필요가 : strtol 함수에 의해

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

검사를

#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; 
} 
관련 문제