Find()返回unsigned int的最大值

find() returning maximum value of unsigned int

本文关键字:int 最大值 unsigned 返回 Find      更新时间:2023-10-16

我正在完成一项家庭作业,该作业要求我在同一个命令中重定向输入和输出。在命令(字符串)中搜索"<"answers">"时,if语句总是返回true。这是因为它在64位系统上查找unsigned int的最大值。

if (uCommand.find("<",0) && uCommand.find(">", 0))语句将始终为真。当我运行u命令时。在GDB中查找(">",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)-1, size_t是无符号类型,这意味着npos是一个非常大的值。你不能把它当作bool,因为任何非零的东西都被当作true

你的代码应该是
if (uCommand.find("<", 0) != std::string::npos && uCommand.find(">", 0)  != std::string::npos)