I need this to read a file and copy it into another file while modifying numbers, everything works except it copies and displays everything in vertical line. Is there a way how to avoid this? For loop seems to be a problem, but what should be added/changed without changing everything else?
Output should be:
9as 3
12as342sd
5678acv
#include <iostream>
#include <fstream>
#include <ctype.h>
using namespace std;
int main()
{
string line;
//For writing text file
//Creating ofstream & ifstream class object
ifstream ini_file {"f.txt"};
ofstream out_file {"f1.txt"};
if(ini_file && out_file){
while(getline(ini_file,line)){
// read each character in input string
for (char ch : line) {
// if current character is a digit
if (isdigit(ch)){
if(ch!=57){ch ;}
else if (ch=57){ch=48;}}
out_file << ch << "\n";}}
cout << "Copy Finished \n";
} else {
//Something went wrong
printf("Cannot read File");
}
//Closing file
ini_file.close();
out_file.close();
return 0;
}
CodePudding user response:
out_file << ch << "\n";}}
I don't know if I understand your problem fully since you didn't give any output, but looks like you should get rid of "\n" in this line. It makes a new line after each character.
CodePudding user response:
Learn to split code to smaller pieces.
Take a look on that:
#include <cctype>
#include <fstream>
#include <iostream>
char increaseDigit(char ch) {
if (std::isdigit(ch)) {
ch = ch == '9' ? '0' : ch 1;
}
return ch;
}
void increaseDigitsIn(std::string& s)
{
for (auto& ch : s) {
ch = increaseDigit(ch);
}
}
void increaseDigitsInStreams(std::istream& in, std::ostream& out)
{
std::string line;
while(out && std::getline(in, line)) {
increaseDigitsIn(line);
out << line << '\n';
}
}
int main()
{
std::ifstream ini_file { "f.txt" };
std::ofstream out_file { "f1.txt" };
increaseDigitsInStreams(ini_file, out_file);
return 0;
}