Answer the question
In order to leave comments, you need to log in
Writing from one text file to another does not work. What to do?
In theory, the program should compare character-by-character the content of two text files (txt1 and txt2) and write the same elements to the third text file (txt3).
#include <iostream>
#include <fstream>
#include <string>
int main(){
//переменные, отвечающие за посимвольный перебор//
char sim1, sim2,n;
//строки, на которые мы ориентируемся//
std::string line;
std::string line2;
//открытие двух материнских файлов для чтения//
std::ifstream txt1("txt.txt");
std::ifstream txt2("txt2.txt");
if (txt1.is_open())
{
if (txt2.is_open())
{
std::cout<<"Файлы txt1 и txt2 открыты"<<std::endl;
//посимвольно сравниваем два файла//
while (txt1.get(sim1),feof)
while (txt2.get(sim2),feof)
//одинаковые элементы записываем в третий//
if (sim1==sim2) {
std::ofstream txt3("txt3.txt");
std::cout<<sim1;
txt3.close();}
}
}
//закрываем файлы//
txt1.close();
txt2.close();
std::cout << "End of program" << std::endl;
return 0;
};
Answer the question
In order to leave comments, you need to log in
#include <iostream>
#include <fstream>
int main() {
// переменные, отвечающие за посимвольный перебор
char sim1, sim2, n;
// abbreviation: not identical
bool ni = false;
// открытие двух материнских файлов для чтения
std::ifstream txt1("txt1.txt");
std::ifstream txt2("txt2.txt");
// открытие файла для записи
std::ofstream txt3("txt3.txt");
if (!txt1.is_open() || !txt2.is_open()) {
std::cout << "I can't open a file for reading" << std::endl;
return 1;
}
if(!txt3.is_open()) {
std::cout << "I can't open a file for writing" << std::endl;
return 1;
}
std::cout << "txt1 and txt2 files are open" << std::endl;
// посимвольное сравниваем два файла
while(!txt1.eof() && !txt2.eof()) {
txt1.get(sim1);
txt2.get(sim2);
if(sim1 == sim2) {
txt3.put(sim1);
} else {
ni = true;
}
}
if(!ni && txt1.eof() && txt2.eof()) {
// сообщение о успехе
std::cout << "The file contents are identical" << std::endl;
} else {
// Если посимвольное сравнение не увенчалось успехом
std::cout << "The contents of the files are not identical" << std::endl;
}
// закрываем файлы
txt1.close();
txt2.close();
txt3.close();
std::cout << "End of program" << std::endl;
return 0;
}
What am I doing wrong?
if (sim1==sim2) {
std::ofstream txt3("txt3.txt");
std::cout<<sim1;
txt3.close();}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question