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
}
당신은 http://en.cppreference.com/ ([strtol''] 사용할 수 있습니다 w/c/string/byte/strtol)이 매우 쉽습니다. 문자열을 숫자 *로 변환하고 *는 숫자가 아닌 문자열을 검사하는 데 도움이됩니다. 그것은 심지어 당신이 지금 문제가있는 음수를 처리 할 것입니다. –
@ user2337345 - 우르 코드는 괜찮습니다. 여기서 당신의 문제는 무엇입니까? 당신은 무엇을 기대하고 있습니까? – arunb2w
@Joachim Pileborg 방금 음수로 코드를 테스트 했으므로 처리 할 수있었습니다. 그러나 '123edf 12'와 같은 입력은 * argv []를 2D 문자 배열로 변환한다는 것이 나에게 발생했습니다. 지금 이것을 확인하려고합니다. – user2337345