在命令行程序中使用布尔值。找不到定义标志并检查它们是否在参数中的方法
Using bool values in a command-line program. Can't find a way to define the flags and check if they are in the parameters
我试着在stackoverflow上到处寻找我的问题,但没有发现类似的问题。我正在执行一项任务,该任务要求我遍历每个参数,如果它是一个文本文件,则为给定的每个参数输出文本文件的长度。
函数的主要部分我没有遇到任何问题。我遇到的唯一问题是,我们必须有特定的标志(表示为"-c"),如果标志在参数中,它将改变主程序的行为。例如,"-c"只输出文本文件的内容,而不是打印出它的长度。
我知道他们使用布尔值,看看标志是否在参数中。然而,无论我尝试什么方法,我的编译器都会不断地想出这个神秘的预期不合格的id。
我的代码以开头
int main(int argc, char *argv[]){
for ( i = 1; 1 < argc; i++) // iterating through each textfiles
}
我想让程序看看argv[I]是否是我定义的标志,但无论我试图用什么方法实现标志,我总是会收到这个错误。
bool isflag (string -c)
或
bool -c;
-c = true;
if (isflag){
...
}
这些都不起作用。我想这和破折号有关。我只是真的有预感,不知道该怎么办才能解决这个问题。
您似乎在变量的名称和存储在该变量中的值之间有点混淆。这里有一段C++代码,展示了如何根据命令行参数检查字符串,并在匹配时设置布尔标志。它假设"-c"将是第一个命令行参数(如果存在的话)。
int main(int argc, char *argv[])
{
std::string argument = "-c"; /* the string you're looking for */
bool flag = false; /* Was the string found? */
int filename_start_position = 1; /* Where do the filenames start in the argument list? */
/* check first argument to see if it's the -c option */
if (argument == argv[1]) /* note, using == for string comparison only works if at least one of the arguments is a std::string */
{
flag = true; /* -c option found, set the flag */
filename_start_position = 2; /*no need to process argv[1] further */
}
/* Process remaining arguments */
for(int i = filename_start_position; i < argc; i++)
{
if (flag)
{
/* print contents of file argv[i] */
}
else
{
/* calculate length of file argv[i] */
}
}
}
相关文章:
- 如何检查给定的参数是否为 cv::noArray()?
- 用于检查值是否为其任何参数的帮助程序函数
- 模板化检查是否存在带有参数列表的类成员函数?
- SFINAE 检查模板参数运算符
- 检查两个模板参数是否相同
- 使用参数包自动执行dynamic_cast检查
- 检查类是否具有模板专用化(使用布尔值或 int 等模板参数)
- 为什么 std::bind 静态类型检查传递给函数的参数?
- 如何检查参数包是否具有执行顺序中的确切类型
- C++编译时检查是否可以用某种类型的参数调用重载函数
- 如何检查模板参数是否为给定值?
- 在编译时检查未实例化的类模板是否继承自其第一个模板参数
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- 如何检查参数包中的每个类型是否唯一
- 如何在C 中检查参数是否通过
- 检查参数是否为空
- 类型 traits,用于检查参数包中的所有类型是否都是可复制构造的
- 一种在编译时用C++根据printf格式检查参数的可移植方法
- EXPECT_CALL检查参数是否包含给定的子集
- 检查参数是否为动态数组.有必要吗?