首页 > 解决方案 > 如何在正常工作的同时修改它?

问题描述

我有一个while在文本文件中搜索单词的循环。如果找到,我想打印一条消息。否则,我想保存输入。这只是功能的一部分。此循环在找到单词之前会保存多次。


while (getline(f, line)) 
{
    if (line.find(token) != string::npos)
    {
        cout <<"\nToken already exists"<< endl;
        break;
    }
    else
    {
        SaveUser();
    }
}

循环SaveUser()在找到单词之前调用该函数。

标签: c++stringloopswhile-loop

解决方案


如果我没有正确理解您,那么您可以将循环体移到循环本身之外。

例如(我使用的是字符串流而不是文件)

#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

您应该插入函数调用,而不是输出短语。


推荐阅读