c++ - 带 I/O 的 C++ 行对齐
问题描述
我正在创建一个程序来证明段落的合理性,以确保每行的长度为 75 个字符。我已经创建了可以插入空格并根据需要创建这些所需长度的函数,但是我在读取文本文件并试图逐行分解它时遇到问题。提供的每一行都小于 75 个字符的限制,当只给出一行时,我的函数可以正常工作。但我不知道如何逐行读取、操作它,然后写入我的新 .txt 文件。当我将它输出到新的文本文件时,我会看到一行合理的文本,而不是段落块中的文本!
我试图创建一个 if else 循环,它只会在 string.length() 小于 75 字符时运行,并且会在 false 时创建一个新行,但我不知道如何在程序中创建这个新行
string myString;
string line("\n");
while (getline(inFile, myString))
{
cout << myString << endl;
puncLoop(myString);
spaceLoop(myString);
}
}
解决方案
为了使用新行输出文件,您可以使用"\n"
.
#include <iostream>
#include <string>
#include <fstream>
int main() {
//in file object
std::ifstream inFile("example.txt");
//out file object
std::ofstream outFile ("example2.txt", std::ios_base::out | std::ios_base::trunc );
//Checking if file exist
if( inFile && outFile )
{
//temp valarable to store each line
std::string mystring;
//Loop through each line
while (getline(inFile, mystring))
{
//... Call Your Business Logic functions here, ( make use of pass by refernce or return to get back the string )
outFile << mystring.c_str() << "\n";
}
//closing file after completing
inFile.close();
outFile.close();
}
else
{
std::cout << "Could not open File to read or write"<<std::endl;
}
return 0;
}
推荐阅读
- docker - 如何使用 Google Secrets Manager 在 Google Cloud Build 中创建 docker ARG?
- javascript - React JS / Node JS:从获取API响应中映射数组与对象的问题
- java - Java 在 readObject() (FileInputstream) 处挂起
- python - 如何尝试以字符串格式捕获异常?
- python - 在 pyttsx3 中使用 Mbrola 声音
- zebra-printers - ZQ210 将 zpl 打印为文本而不更改 device.languages
- sqlite - 使用 Objective-C 和 SQLite,在 DB 中循环思考记录并为每一行设置一个递增的值
- airflow - 空气流动。仅当第一个任务的结果为真时才运行第二个任务
- python - Pandas/Python 在图表上绘制数据点
- git - 获取远程服务器上两次提交之间的所有提交?