Splitting strings by newline character in C++

synaptik picture synaptik · Jun 1, 2013 · Viewed 9.3k times · Source

If I have two tables stored in std::string variables, how could I display them side-by-side? In particular...

I have std::string table1 which contains the following:

 X | Y
-------
 2 | 3
 1 | 3
 5 | 2

I have std::string table2 which contains the following:

 X | Y
-------
 1 | 6
 1 | 1
 2 | 1
 3 | 5
 2 | 3

I need to modify them (or really just print them to standard output) so that the following appears:

 X | Y    X | Y
-------  -------
 2 | 3    1 | 6
 1 | 3    1 | 1
 5 | 2    2 | 1
          3 | 5
          2 | 3

In other words, I have two tables stored in std::string variables with newline characters separating the rows.

I would like to print them to screen (using std::cout) so that the tables appear side-by-side, vertically aligned at the top. How could I do this?

For example, if I could do something like std::cout << table1.nextToken('\n') where nextToken('\n') gives the next token and tokens are separated by the '\n' character, then I could devise a method to cycle through all tokens, and once all of table1 tokens are used, I could then simply print space characters so that the remaining tokens of table2 are properly horizontally aligned. But, such a nextToken(std::string) function does not exist --- I don't know of it, at least.

Answer

mika314 picture mika314 · Jun 1, 2013

Key words: istringstream, getline

Implementaion:

#include <iostream>
#include <sstream>
int main()
{
    std::string table1 = 
        " X | Y\n"
        "-------\n"
        " 2 | 3\n"
        " 1 | 3\n"
        " 5 | 2\n";
    std::string table2 = 
        " X | Y\n"
        "-------\n"
        " 1 | 6\n"
        " 1 | 1\n"
        " 2 | 1\n"
        " 3 | 5\n"
        " 2 | 3\n";

    std::istringstream streamTable1(table1);
    std::istringstream streamTable2(table2);
    while (!streamTable1.eof() || !streamTable2.eof())
    {
        std::string s1;
        getline(streamTable1, s1);
        while (s1.size() < 9)
            s1 += " ";
        std::string s2;
        getline(streamTable2, s2);
        std::cout << s1 << s2 << std::endl;
    }
}