首页 > 解决方案 > 带 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);
}

}

标签: c++stringio

解决方案


为了使用新行输出文件,您可以使用"\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;
}

推荐阅读