c++ - 如何在正常工作的同时修改它?
问题描述
我有一个while
在文本文件中搜索单词的循环。如果找到,我想打印一条消息。否则,我想保存输入。这只是功能的一部分。此循环在找到单词之前会保存多次。
while (getline(f, line))
{
if (line.find(token) != string::npos)
{
cout <<"\nToken already exists"<< endl;
break;
}
else
{
SaveUser();
}
}
循环SaveUser()
在找到单词之前调用该函数。
解决方案
如果我没有正确理解您,那么您可以将循环体移到循环本身之外。
例如(我使用的是字符串流而不是文件)
#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
您应该插入函数调用,而不是输出短语。
推荐阅读
- xamarin - 活动没有通过 super.onresume 异常调用
- javascript - 通过带有索引的jquery ajax发送php数组并接收数组值
- algorithm - 将数字分成三组
- algorithm - 从 100 万个对象的列表中搜索
- c# - “内部”变量通过函数
- git - 将 Go Dep 与私有 Gitlab 存储库一起使用
- hadoop - Hadoop on Mesos 需要高性能集群虚拟化
- java - 我的问题是,当我试图打开它的 fxml 文件时,我在 netbeans 中打开了一个 github 项目场景构建器说:无法打开 login.fxml 文件
- azure - 将数据从 Azure 流分析存储到 Blob 存储时,是否可以在路径中添加 DeviceID
- go - Axios 和 fetch 在 Golang 中提供空映射,即使是 url 编码(添加了标头)