【问题标题】:C++ line justification with I/O带 I/O 的 C++ 行对齐
【发布时间】:2020-02-18 04:20:18
【问题描述】:

我正在创建一个程序来证明段落的合理性,以确保每行的长度为 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++ string io


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-05-24
      • 2014-04-30
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      相关资源
      最近更新 更多