问题描述
这是我用来从txt文件检测一行中的字符串的代码:
Here is the code I used to detect the string in a line from a txt file:
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",因此它将执行:
The error is, the program will not go to find "GetSphereSAandVol", because it stops at "GetSA". Obviously, the program thinks "GetSphereSAandVol" contains "GetSA", so it will execute:
if(found = line.find("GetSA"))
std::cout<<"We found GetSA."<<std::endl;
这并不是我想要的,因为我希望程序能够执行:
which is not exactly what I want, because I am expecting the program to execute:
else if (found = line.find("GetSphereSAandVol"))
std::cout<<"We found GetSphereSAandVol."<<std::endl;
因此,无论如何我都可以避免这种情况?得到我真正想要的?非常感谢.
So, anyway I can avoid this? to get what I really want? Thanks a lot.
推荐答案
您误解了find
的工作方式.阅读文档.
You misunderstand how find
works. Read the documentation.
条件句应该这样:
if ((found = line.find("xyz")) != line.npos) { /* found "xyz" */ }
我会这样编写整个程序:
I would write your entire program like this:
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 ++中找到完全匹配的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!