gpt4 book ai didi

C++接受带参数的命令行参数

转载 作者:太空狗 更新时间:2023-10-29 21:22:46 26 4
gpt4 key购买 nike

我有一个程序需要接受多个命令行参数。我已经到了需要将其设置为接受参数 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;

最佳答案

From this page :

This variable is set by getopt to point at the value of the option argument, for those options that accept arguments.

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
}

编辑

Reference link

如果您能够使用 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;
}

关于C++接受带参数的命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19918992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com