getline读取同一行(c++,istream)
getline reads same line (C++,istream)
我试着在两个文本文件之间找到相同的行。
while (getline (texta,str1)){
while (getline (textb,str2)){
cout<<str1<<str2<<endl;
}}
第一个工作得很好,但第二个只是阅读第一部分文本,然后退出。我试过不同的文本,但不工作。
查看所有代码:
void similars(string text1,string text2){
string str1,str2;
ifstream texta(text1.c_str());
ifstream textb(text2.c_str());
if(texta.is_open() && textb.is_open()){
while (getline (texta,str1)){
while (getline (textb,str2){
cout<<str1<<str2<<endl;
}
}
}
else cout << "Unable to open file";
}
不要把不该做的事情混在一起考虑这个例子:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void similars(string text1, string text2)
{
string str1, str2;
ifstream texta(text1.c_str(), ios::in);
ifstream textb(text2.c_str(), ios::in);
cout << "text1: " << endl << endl;
while(!texta.eof())
{
getline (texta, str1);
cout << str1 << endl;
}
cout << endl << endl;
texta.close(); // closing safely the file
cout << "text2: " << endl << endl;
while(!textb.eof())
{
getline (textb, str2, 'n');
cout << str2 << endl;
}
textb.close();
cout << endl;
}
int main()
{
system("color 1f");
string sText1 = "data1.txt";
string sText2 = "data2.txt";
similars(sText1, sText2);
system("pause");
return 0;
}
只需用记事本或任何文本编辑器创建两个文本文件,将其重命名为"text1.txt","text2.txt",并在其中放入一些文本,保存并关闭。然后运行程序
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 从C++dll访问C#中的一行主要参数
- 在C++中,我如何接受不同于同一行的用户输入
- 如何从一行中读取特定数量的字符?(C++)
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 有没有办法在一行中填充矢量图
- 需要将一行代码从C++ Qt翻译成PyQt
- 为什么如果我添加这一行,我的程序会不断询问值
- 如何使代码打印文本文件中的第一行?
- 如何在C++中以这种方式返回一行文本?
- 如何使用运算符在同一行中多次调用函数
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 而(!inputfile.eof())只读取第一行?
- 这段代码的最后一行在做什么?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- C++找出覆盖同一行的数组
- 如何让字符数组在一行而不是多行中打印出来?