如何逐行读取文件的内容
How to read contents of a file line by line
hy。。。我的程序只是在文件中输入文本行。然后,它将一行作为用户的输入,并检查它是否存在于文件中。如果是,则显示"已找到",否则显示"未找到"。问题是,在读取文件时,它只检查文件中的最后一行,并显示前几行的"未找到"。请指导我如何逐一阅读所有行,并将它们与输入字符串进行比较。
#include<iostream>
#include<fstream>
#include<string>
#include<conio.h>
using namespace std;
void main()
{
int x=0,y=1;
string f;
while(x!=1){
ofstream myfile("try.txt",ios::app);
if(myfile.is_open())
{
cin>>f;
myfile << f <<endl;
myfile.close();
}
else
{cout<<"file could not be opened";}
cout<<"enter more?"<<endl;
cin>>x;
}
string line;
string a;
cin>>a;
ifstream yfile("try.txt");
if(yfile.is_open())
{
while(getline (yfile,line))
{
if(line==a)
{y=0;}
else
{y++;}
}
if(y==0)
{cout<<"found"<<endl;}
else
{cout<<"match not found"<<endl;}
yfile.close();
}
getch();
}
当您进行匹配时,您需要突破while循环
while(getline (yfile,line))
{
if(line==a)
{
y=0;
break; //<--- match found so exit loop
}
else
{
y++;
}
}
否则,当遇到不匹配时,您将覆盖以前找到的任何匹配项(因为y
会递增,并且您特别选中y == 0
以打印匹配消息)。因此,如果最后一行不匹配,则不会检测到
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量