我有一个while
循环,用于在文本文件中搜索单词。如果找到,我要打印一条消息。否则,我要保存输入。这只是功能的一部分。在找到单词之前,此循环可以保存多次。
while (getline(f, line))
{
if (line.find(token) != string::npos)
{
cout <<"\nToken already exists"<< endl;
break;
}
else
{
SaveUser();
}
}
循环在找到单词之前调用函数SaveUser()
。
答案 0 :(得分:1)
如果我正确理解了您的意思,则可以将循环的主体移到循环本身之外。
例如(我使用的是字符串流而不是文件)
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string s( "Hello Imre_talpa\nBye Imre_talpa\n" );
std::istringstream is( s );
bool found = false;
std::string line;
while ( ( found = ( bool )std::getline( is, line ) ) and ( line.find( "Bye" ) == std::string::npos ) );
if ( found )
{
std::cout << "\nToken already exists" << '\n';
}
else
{
std::cout <<"\nHere we're saving the input" << '\n';
}
}
程序输出为
Token already exists
如果您将字符串“ Bye”更改为字符串流(在您的情况下为文件)中不存在的任何其他字符串,则输出为
Here we're saving the input
您应该插入函数调用,而不是输出短语。