我是C的新手,想要编写一个简单的程序,用两个命令行参数调用(第一个是程序的名称,第二个是字符串).我已经验证了参数的数量,现在想验证输入只包含数字.
#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;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然上面的代码没有抛出错误,但它没有正确验证输入,我无法弄清楚原因.有人能指出我正确的方向吗?
非常感谢提前和所有最好的
if (argc != 2)
Run Code Online (Sandbox Code Playgroud)
一定是
if (argc == 2)
Run Code Online (Sandbox Code Playgroud)
干
if isdigit(argv[1][i])
{
printf("Success!\n");
}
Run Code Online (Sandbox Code Playgroud)
如果数字有4位数,您将打印"成功"4次,更好地做以下事情:
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;
Run Code Online (Sandbox Code Playgroud)
示例:
#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;
}
Run Code Online (Sandbox Code Playgroud)
编译和执行:
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 $
Run Code Online (Sandbox Code Playgroud)
在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)
Run Code Online (Sandbox Code Playgroud)