简单的c++文件读取使用if流
Simple c++ file reading using if stream
我似乎不能让这个简单的代码工作。我想打开一个文本文件,并使用以下函数将每行与一个单词进行比较:
ifstream ifs("wordsEn.txt");
bool findword (string word)
{
string currentword="";
if (!ifs.is_open()) {
cout << "error" <<endl;
return false;
}
while(getline(ifs, currentword)) {
if (currentword == word) {
cout<< "true" <<endl;
return true;
}
}
return false;
}
虽然这应该可以工作,但是这个函数永远不会返回true。我知道这是非常基本的,但是我找不到我的错误
将while
中的条件替换为
while (ifs >> currentword)
,它应该可以工作。你现在读的是整行,而不是一个字一个字地读。如果您想逐行读取,则需要进一步对每行进行标记(例如使用std::istringstream
)。
EDIT 1即使你在文件中每行有一个单词,你也必须绝对确保你在它之前/之后没有任何额外的空白,因为如果你这样做,那么字符串将是类似"word"的东西,而不是"word"。这就是为什么直接使用提取操作符更安全,因为默认情况下它会跳过空格。
EDIT 2现代c++编写搜索函数的方式看起来更像
bool findword (const std::string& word) {
std::istream_iterator<std::string> it_beg(ifs); // need to #include <iterator>
std::istream_iterator<std::string> it_end{};
return (std::find(it_beg, it_end, word) != it_end); // need to #include <algorithm>
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++如何正确实现并行IF流读取
- 使用"IF" C++逐行读取文本文件
- C# 读取完全锁定的文本文件或读取 if 语句外部的输出
- 控制台将继续关闭,而不是读取 if 语句中的字符串
- 不会让我在 IF 语句(家庭作业)之后读取用户输入
- c++ 读取左 IF 语句条件和右语句条件
- C++ if 语句不起作用(不会读取内存)
- 简单的c++文件读取使用if流
- c++从文件中读取:使用.fail()或try/catch的if条件
- for 循环的问题,它同时读取 if 和 else if 语句
- c++ if命令读取为真,尽管为假
- c++不读取IF/Else语句