2015-10-08 95 views
0

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

if (uCommand.find("<",0) && uCommand.find(">", 0))声明将始终为真。当我运行uCommand.find( “>”,0)在gdb的回报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); 

}

+0

最大的无符号整型是-1,如果interpretted作为一个符号整型。你确定它不返回一个有符号的int吗? –

回答

2

我假设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) 
+0

这个伎俩。任何想法为什么GDB显示它是上述数字而不是-1? –

+0

我稍微更新了我的答案以使用'size_t'。由于它是无符号的,所以当强制转换size_t时,值为-1会产生巨大的值。 –