在命令行中声明-n参数以接受整数-C [英] Declaring a -n argument to accept an integer in the command line - C
问题描述
我正在编写一个程序来打印.txt
文件的最后n
个字符.我希望添加使用-n
参数从命令行运行程序的功能,以输入要打印的字符数.
I am writing a program to print the last n
characters of a .txt
file. I wish to add the ability to run the program from the command line with a -n
argument to input the amount of characters to print.
我尝试声明int main(int argc, char* argv[])
,但这似乎接受任何数量的参数,而我只需要一个-n
参数.
I have tried declaring int main(int argc, char* argv[])
but that seems to accept any amount of arguments and I only need the one -n
argument.
推荐答案
为此,您可以使用strncmp
和strtol
:
int main(int argc, char* argv[])
{
int n = 0;
if(argc > 1)
{
if(!strncmp(argv[1], "-n", 2))
{
n = strtoll(argv[1]+2, NULL, 10);
}
}
if(n == 0) /* fail */;
/* do stuff */
}
这将检查argv
是否具有多个参数(程序名称),然后检查-n
,如果找到它,则将-n
之后的数字直接转换为整数(即-n3
转换为三).
This checks if argv
has more than just one argument (the name of the program) and then checks for -n
, and, if it finds it, converts the number directly after -n
to an integer (i.e. -n3
is converted to three).
如果您只想接受一个参数,否则将失败,请将argc > 1
更改为argc == 2
.
If you want to accept one argument only and fail otherwise, change argc > 1
to argc == 2
.
这篇关于在命令行中声明-n参数以接受整数-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!