这是我用来从 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;
那么,无论如何我可以避免这种情况吗?得到我真正想要的东西?非常感谢。