在命令行中声明-n参数以接受整数-C [英] Declaring a -n argument to accept an integer in the command line - C

查看:88
本文介绍了在命令行中声明-n参数以接受整数-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.

推荐答案

为此,您可以使用strncmpstrtol:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆