这是我用来从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";
}
}