简体   繁体   中英

find() returning maximum value of unsigned int

I'm finishing up a homework assignment that requires me to redirect input and output in the same command. When searching the command (that is a string) for both "<" and ">" the if statement always returns true. This is because it finds the maximum value of an unsigned int on a 64bit system.

The if (uCommand.find("<",0) && uCommand.find(">", 0)) statement will always be true. When I run the uCommand.find(">", 0) in gdb is returns 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);

}

I'm assuming uCommand is a std::string , as you didn't include its declaration.

std::string::find returns std::string::npos when the find fails to find anything. This is normally (size_t)-1 , size_t is an unsigned type, meaning that npos is an extremely large value. You can't treat this as a bool as anything non-zero is treated as true .

Your code should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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