C++ 接受带参数的命令行参数
C++ Accepting a command-line argument with parameters
我有一个需要接受多个命令行参数的程序。我已经到了需要将其设置为接受参数 n 的阶段,该参数指定最终将打印的字符串的最大和最小长度。基本上输入可能如下所示:
-a -n7,7 -i // with -a and -i being other arguments
我可以自己挑选参数,但我不确定如何提取这些最大值和最小值。我已经尝试过(见下文),但是每当我尝试使用最小值和最大值变量时,我都会出现运行时错误。干杯伙计们。
int c;
while ((c = getopt(argc, argv, ":wpsaevin")) != -1) {
switch (c) {
case 'w': // pattern matches whole word
mode = WHOLE;
break;
case 'p': // pattern matches prefix
mode = PREFIX;
break;
case 'a': // pattern matches anywhere
mode = ANYWHERE;
break;
case 's': // pattern matches suffix
mode = SUFFIX;
break;
case 'e': // pattern matches anywhere
mode = EMBEDDED;
break;
case 'v': // reverse sense of match
reverse_match = true;
break;
case 'i': // ignore case of pattern
ignore_case = true;
break;
case 'n': //Specifies word length
length_spec = true;
cin >> minimum >> maximum;
if (minimum == 0 && maximum == 0) { //no word limit
length_spec = false;
} else if (maximum == 0) {
maximum = 100;
}
break;
}
}
argc -= optind;
argv += optind;
从此页面:
此变量由getopt设置为指向选项的值 参数,用于接受参数的选项。
case 'n': //Specifies word length
length_spec = true;
char *cvalue = optarg;
// TODO: Split cvalue by delimiter
// to obtain minimum and maximum
if (minimum == 0 && maximum == 0) { //no word limit
length_spec = false;
} else if (maximum == 0) {
maximum = 100;
}
break;
以及拆分字符串的示例:
#include <iostream>
#include <string>
#include <algorithm>
int
main()
{
const char* test = "1000,2000";
std::string str = std::string(test);
auto find = std::find(str.begin(), str.end(), ',');
std::string first = std::string(str.begin(), find);
std::string second = std::string(find+1,str.end());
std::cout << first << " " << second;
// 1000 2000
}
编辑
参考链接
如果您能够使用 C++11,请考虑使用 std::stoi
,如下所示:
int first_int = std::stoi( first );
int second_int = std::stoi ( second );
如果没有,请尝试以下操作:
std::replace(str.begin(), str.end(), ',', ' ');
std::istringstream ss(str);
ss >> first_int;
ss >> second_int;
std::cout << first_int << " " << second_int << std::endl;
我会把atoi
作为最后的手段。
朴素的实现可能如下所示(使用风险自负):
int convert(std::string s)
{
int size = s.size();
int exp = size - 1;
int result = 0;
for (int i = 0; i < size; i++)
{
char c = s[i];
result += (int)(c - '0') * std::pow(10, exp--);
}
return result;
}
您可以使用 Boost Library Program Options,如上所述@aaronman。
相关文章:
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何处理linux终端中带有负号(-)的C++中的命令行参数
- 使用 C++ 将命令行参数拆分为参数/向量
- 如何在OMNET++中添加专门的命令行参数?
- 如何在不传递命令行参数的情况下在 c++ 中设置环境变量
- atoi() 在应用于大型命令行参数时会产生不正确的值
- 是否可以在命令行中将输入参数传递给可执行文件
- 命令行参数,cant 或两个变量
- 在 Windows 中使用 boost::p rogram_options 从命令行参数读取 Unicode 字符
- 如何在 Android/NDK 上将命令行参数从 gradlew.bat 传递到 Clang
- 编写一个将 LLVM IR 文件作为命令行参数的程序
- 通过命令行参数获取llvm ir文件时面临问题
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- 从命令行获取参数时出现问题
- 如何在不使用文件扩展名的情况下使用命令行参数打开C++中的文本文件?
- 命令行参数在不到 3 个 LOC 中 int?
- 在命令行参数中使用引号
- 使用参数 + stdout + stderr 从命令行调用 MFC 应用程序
- 在VS2013中使用devenv (C++)传递命令行参数argv
- 二进制数据作为命令行参数