gpt4 book ai didi

c++ - 在 C++ 中查找精确的字符串匹配

转载 作者:太空狗 更新时间:2023-10-29 23:46:13 24 4
gpt4 key购买 nike

这是我用来检测 txt 文件中一行字符串的代码:

int main()
{
std::ifstream file( "C:\\log.txt" );

std::string line;
while(!file.eof())
{
while( std::getline( file, line ) )
{
int found = -1;
if((found = line.find("GetSA"))>-1)
std::cout<<"We found GetSA."<<std::endl;
else if ((found = line.find("GetVol"))>-1)
std::cout<<"We found GetVol."<<std::endl;
else if ((found = line.find("GetSphereSAandVol"))>-1)
std::cout<<"We found GetSphereSAandVol."<<std::endl;
else
std::cout<<"We found nothing!"<<std::endl;

}
}
std::cin.get();
}

这是我的日志文件:

GetSA (3.000000)

GetVol (3.000000)

GetSphereSAandVol (3.000000)

GetVol (3.000000)

GetSphereSAandVol (3.000000)

GetSA (3.00000)

错误是,程序不会去寻找“GetSphereSAandVol”,因为它停在了“GetSA”处。显然,程序认为“GetSphereSAandVol”中包含“GetSA”,所以会执行:

if(found = line.find("GetSA"))
std::cout<<"We found GetSA."<<std::endl;

这不是我想要的,因为我希望程序执行:

else if (found = line.find("GetSphereSAandVol"))
std::cout<<"We found GetSphereSAandVol."<<std::endl;

那么,无论如何我都可以避免这种情况?得到我真正想要的?非常感谢。

最佳答案

您误解了find 的工作原理。阅读 documentation .

条件应该是这样的:

if ((found = line.find("xyz")) != line.npos) { /* found "xyz" */ }

我会这样写你的整个程序:

int main(int argc, char * argv[])
{
if (argc != 2) { std::cout << "Bad invocation\n"; return 0; }

std::ifstream infile(argv[1]);

if (!infile) { std::cout << "Bad filename '" << argv[1] << "'\n"; return 0; }

for (std::string line; std::getline(infile, line); )
{
int pos;

if ((pos = line.find("abc")) != line.npos)
{
std::cout << "Found line 'abc'\n";
continue;
}

if ((pos = line.find("xyz")) != line.npos)
{
std::cout << "Found line 'xyz'\n";
continue;
}

// ...

std::cout << "Line '" << line << "' did not match anything.\n";
}
}

关于c++ - 在 C++ 中查找精确的字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13020526/

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