我需要这个来读取一个文件,并将它复制到另一个文件中,同时修改数字,除了它复制和显示所有的垂直线外,一切都正常工作。有办法避免这种情况吗?For循环似乎是一个问题,但是在不更改其他所有内容的情况下,应该添加/更改什么呢?
产出应是:
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;
}发布于 2022-03-09 14:20:21
学习将代码分割成更小的部分。
看一看:
#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;
}https://stackoverflow.com/questions/71410527
复制相似问题