Home > Back-end >  How to print multiple lines of text in C
How to print multiple lines of text in C

Time:12-25

So, say I want to print 500 lines of regular text ( an essay or something of the sort ) using C . The thing is, I don't want to have to put cout << << endl; in each line of text manually ( since it would take a while ). Is there a way I could make an array to print out the lines of text ( or is there any other function that exists)?

CodePudding user response:

Yes, you can put your strings in an array, best a dynamic array that can grow, depending on how many lines of input you have.

For this, we use the std::vector in C . It is a very often used working horse for that kind of applications.

I will use an example and read some lines of text from a file and store them in a std::vector.

Some simple example:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main() {

    // Open file with text
    std::ifstream fileStream("test.txt");

    // If file is open
    if (fileStream) {

        // Here we will store one line, that we read from a text file
        std::string line{};

        // And here we will store all lines from the file in a std::vector
        std::vector<std::string> text{};


        // Now read line by line from the text file
        while (std::getline(fileStream, line)) {

            // Add line to text
            text.push_back(line);
        } // Now all lines have been read
    }
    else std::cerr << "\n*** Error: Could not open text file\n";
}

Now you have many different possibilities, to write all the lines to std::cout.

The most simple ist the range based for loop.

This we will use in the next example code:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main() {

    // Open file with text
    std::ifstream fileStream("test.txt");

    // If file is open
    if (fileStream) {

        // Here we will store one line, that we read from a text file
        std::string line{};

        // And here we will store all lines from the file in a std::vector
        std::vector<std::string> text{};


        // Now read line by line from the text file
        while (std::getline(fileStream, line)) {

            // Add line to text
            text.push_back(line);
        }

        // Output all lines from text
        for (const std::string& oneLine : text)
            std::cout << oneLine << '\n';
    }
    else std::cerr << "\n*** Error: Could not open text file\n";
}

More advanced users would use std::copyfrom the algorithm library and ostream_iterators, like for example in:

std::copy(text.begin(), text.end(), std::ostream_iterator<std::string>(std::cout,"\n"));

But I doubt that this is more readable . . .

CodePudding user response:

If the text shall be part of the program, you could just use one large string and print that at once, e.g.

const char essay[] = "Line 1\n"
"Line 2\n"
"This is the third line\n"
"and so on\n"
// ...
"until the last line\n";

This will concatenate the lines as one large string at compile time. And to print all the lines, you can now write

std::cout << essay;

CodePudding user response:

Example with programmable line length (note the input string doesn't have newlines). Live demo here : https://onlinegdb.com/X64mU7UPl

#include <string>
#include <iostream>
#include <sstream>

std::string text
{
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "
    "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. "
    "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. "
    "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." 
};

void output(const std::string& string, const std::size_t line_length)
{
    std::istringstream stream{ string };
    std::size_t pos{ 0ul };
    std::string word;

    while (stream >> word)
    {
        if (pos   word.size() > line_length)
        {
            std::cout << "\n";
            std::cout << word;
            pos = word.size();
        }
        else
        {
            std::cout << word;
            std::cout << " ";
            pos  = word.size();
        }
    }
};

int main()
{
    output(text, 40ul);
    return 0;
}
  •  Tags:  
  • c
  • Related