我必须创建一个程序,该程序在A组文件中获取字符串,并将它们与B组的字符串进行比较,创建视频输出,结果等于输出视频文件。群组文件的结构如下:Jhon Smith' \ n' Fergus McDonald' \ n' Elizabeth Harris' \ n'。我有嵌套while循环的问题,最后一个检查A的名字是否等于B的名称似乎工作,但其他两个不是,第一次内循环工作,但然后另一个没有,if条件似乎没有更多的工作,并重复文件元素的数量的文件的所有名称,反之亦然第二组嵌套while循环,我不明白是什么错误
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string As, Bs, Cs;
ifstream A("Group_A.txt");
ifstream B("Group_B.txt");
ofstream C("Result.txt");
if(!A)
{
cout<<"Group A does not exist!";
return -1;
}
if(!B)
{
cout<<"Group B does not exist!!";
return -1;
}
if(!C)
{
cout<<"Failed to create file!!";
return -1;
}
C<<"Elements in A but not in B:"<<endl;
while(getline (B,Bs))
{
while(getline (A,As))
{
if (As != Bs)
{
C<<As<<endl;
}
}
A.clear();
A.seekg(0);
}
A.close();
B.close();
C<<endl;
A.open("Group_A.txt");
B.open("Group_B.txt");
C<<"Elements in B but not in A:"<<endl;
while(getline (A,As))
{
while(getline (B,Bs))
{
if (Bs != As)
{
C<<Bs<<endl;
}
}
B.clear();
B.seekg(0);
}
A.close();
B.close();
C<<endl;
A.open("Group_A.txt");
B.open("Group_B.txt");
C<<"Elements present in both A and B:"<<endl;
while(getline (A,As))
{
while(getline (B,Bs))
{
if (As == Bs)
{
C<<Bs<<endl;
}
}
B.clear();
B.seekg(0);
}
A.close();
B.close();
C<<endl;
C.close();
ifstream res("Result.txt");
while(res >> Cs)
cout<<Cs<<endl;
system ("PAUSE");
return 0;
}
答案 0 :(得分:0)
// write a function that load your file
template <class Itr>
void read_file(std::string const& name, Itr to) {
std::ifstream in(name);
for (std::string line; std::getline(in, line); *itr++ = std::move(line));
}
// load your files
std::set<std::string> a;
read_file("a.txt", std::inserter(a));
std::set<std::string> b;
read_file("b.txt", std::inserter(b));
// based on what you need use one of set algorithms
// from the standard library
// I assumeed you need the union of the two in the below code
std::vector<std::string> c;
std::set_union(a.begin(), a.end(), b.begin, b.end(), std::back_inserter(c));
// dump the result
std::ofstream out("c.txt");
std::copy(c.begin(), c.end(), std::ostream_iterator(out, "\n"));
答案 1 :(得分:0)
问题:
Integer value = order.get(Character.toLowerCase(c));
假设文件A包含1,2,3,文件B包含2,3,4
测试将如下所示:
foreach B in file B
foreach A in file A
if (A != B)
output A
输出文件将包含1,3,1,2,1,2,3
你想要做的是建立文件A和B的集合交集(让我们称之为AnB)。这给你第三个循环。 A和B都是。
将AnB与A进行比较。因此,A中的所有内容都不在B中。是A而不是B.重复B
或者您可以致电std::set_intersection和std::set_difference
2 != 1: true, output 1
2 != 2: false, no output
2 != 3: true, output 3
3 != 1: true, output 1
3 != 2: true, output 2
3 != 3: false, no output
4 != 1: true, output 1
4 != 2: true, output 2
4 != 3: true, output 3