在命令行程序中使用布尔值。找不到定义标志并检查它们是否在参数中的方法

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

本文关键字:检查 参数 方法 是否 定义 程序 命令行 布尔值 找不到 标志      更新时间:2023-10-16

我试着在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] */
}
}    
}