繁体   English   中英

find()返回无符号int的最大值

[英]find() returning maximum value of unsigned int

我正在完成一项作业,需要我在同一命令中重定向输入和输出。 在命令(即字符串)中搜索“ <”和“>”时,if语句始终返回true。 这是因为它会在64位系统上找到unsigned int的最大值。

if (uCommand.find("<",0) && uCommand.find(">", 0))语句将始终为true。 当我在gdb中运行uCommand.find(“>”,0)时会返回18446744073709551615。

int main(int argc, char *argv[]) {
// local variables
char **toks;
int retval;
int ii;
int redirect;
int search;
string fileName;

// initialize local variables
toks = NULL;
retval = 0;
ii = 0;

// main (infinite) loop
while (true)
{
    // get arguments
    toks = gettoks();

    if (toks[0] != NULL)
    {
        for (ii = 0; toks[ii] != NULL; ii++) {
            uCommand += " ";
            uCommand += (string)toks[ii];
        }
        // Search for input, output, or dual redirection
        if (uCommand.find("<", 0) && uCommand.find(">", 0))
        {
            redirect = dualRedirect(toks, uCommand);
            addHist(uCommand);
        }
        else if (uCommand.find("<", 0)) {
            redirect = inRedirect(toks, uCommand);
            addHist(uCommand);
        }
        else if (uCommand.find(">", 0)) {
            redirect = outRedirect(toks, uCommand);
            addHist(uCommand);
        }

        // Look for hist or r and execute the relevant functions
        if (!strcmp(toks[0], "r"))
            repeatCommand(uCommand);
        else if (!strcmp(toks[0], "hist")) {
            addHist(uCommand);
            showHist();
        }
        else if (redirect == 0) {
            execCommand(toks);
            addHist(uCommand);
        }

        // Increment the command count.  This only runs if a something is entered
        // on the command line.  Blank lines do not increment this value.
        commandCount++;
    }
}

// return to calling environment
return(retval);

}

我假设uCommandstd::string ,因为您没有包括它的声明。

当找不到任何东西时, std::string::find返回std::string::npos 通常为(size_t)-1size_t是无符号类型,这意味着npos是一个非常大的值。 您不能将其视为bool因为任何非零值都将被视为true

您的代码应为

if (uCommand.find("<", 0) != std::string::npos && uCommand.find(">", 0)  != std::string::npos)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM