gpt4 book ai didi

c++ - find() 返回 unsigned int 的最大值

转载 作者:行者123 更新时间:2023-11-28 02:19:34 26 4
gpt4 key购买 nike

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

if (uCommand.find("<",0) && uCommand.find(">", 0))声明将永远为真。当我在 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);

最佳答案

我假设 uCommand 是一个 std::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)

关于c++ - find() 返回 unsigned int 的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33006070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com