0
我试图让我的代码向我输入错误消息,如果输入包含除数字以外的任何内容。的输入被接收如下检查字符数组是否包含纯数字或纯字符
int main(int argc, char *argv[]) {
而且它接收该输入如下(I终端期间经由执行值传递)
//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
}
您可以使用['strtol'](http://en.cppreference.com/ w/c/string/byte/strtol)非常简单。它会将字符串转换为数字*和*帮助您检查非数字字符串。它甚至会处理负数,你现在有一个问题。 –
@ user2337345 - 乌尔代码没问题。你在这里遇到什么问题?你在期待什么? – arunb2w
@Joachim Pileborg我刚刚用负数测试了我的代码,它能够处理它。但是,我发现像'123edf 12'这样的输入会将* argv []转换为2D char数组。现在去检查一下。 – user2337345