检查命令行输入是否为数字 [英] check that command line input is numeric
问题描述
我是C语言的新手,想编写一个简单的程序,用正好两个命令行参数来调用(第一个是程序的名称,第二个是字符串)。
我已经验证了参数的 number ,现在想验证输入中仅包含数字。
I'm new to C and want to write a simple programme to be called with exactly two command line arguments (the first one being the programme's name, the second one being a string). I have validated the number of arguments and now want to validate the input only contains digits.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <cs50.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if isdigit(argv[1][i])
{
printf("Success!\n");
}
else
{
printf("Error. Second argument can be numbers only\n");
return 1;
}
}
else
{
printf("Error. Second argument can be numbers only\n");
return 1;
}
}
虽然上面的代码没有引发错误,但是无法正确验证输入,我不知道为什么。有人可以指出我正确的方向吗?
While the above code doesn't throw errors, it doesn't correctly validate the input and I can't figure out why. Could someone point me in the right direction?
请多多关照,并尽一切努力
Thanks a lot in advance and all the best
推荐答案
if (argc != 2)
必须是
if (argc == 2)
做
Doing
if isdigit(argv[1][i])
{
printf("Success!\n");
}
如果数字有4位数字,则您将打印4次成功,更好做类似的事情:
you will print "Success" 4 times if the number has 4 digits, better to do something like :
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (!isdigit(argv[1][i])
{
printf("Error. Second argument can be numbers only\n");
return 1;
}
}
printf("Success!\n");
return 0;
示例:
Example :
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char * argv[])
{
if (argc == 2)
{
int i, n;
for (i = 0, n = strlen(argv[1]); i < n; i++)
{
if (!isdigit(argv[1][i]))
{
printf("Error. Second argument can be numbers only\n");
return 1;
}
}
printf("Success!\n");
}
else {
puts("argument is missing");
return 1;
}
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
argument is missing
pi@raspberrypi:/tmp $ ./a.out az
Error. Second argument can be numbers only
pi@raspberrypi:/tmp $ ./a.out 12
Success!
pi@raspberrypi:/tmp $ ./a.out 12a
Error. Second argument can be numbers only
pi@raspberrypi:/tmp $
在valgrind下执行:
Execution under valgrind :
pi@raspberrypi:/tmp $ valgrind ./a.out 123
==2051== Memcheck, a memory error detector
==2051== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2051== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==2051== Command: ./a.out 123
==2051==
Success!
==2051==
==2051== HEAP SUMMARY:
==2051== in use at exit: 0 bytes in 0 blocks
==2051== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==2051==
==2051== All heap blocks were freed -- no leaks are possible
==2051==
==2051== For counts of detected and suppressed errors, rerun with: -v
==2051== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
这篇关于检查命令行输入是否为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!