如何避免C++中的文本垂直输出



我需要这个来读取一个文件,并在修改数字时将其复制到另一个文件中,除了它以垂直线复制和显示所有内容外,其他一切都可以工作。有办法避免这种情况吗?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;
}

out_file << ch << "n";}}

我不知道我是否完全理解你的问题,因为你没有给出任何输出,但看起来你应该摆脱"\n〃;在这一行。它在每个字符后面都画一条新行。

学习将代码拆分为更小的部分。

看看这个:

#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;
}

最新更新