dimanche 15 septembre 2019

format two columns regardless of row size

I have two columns: one new word and one old word. I can't get them to be alienated to the left. The two columns should be formatted regardless of the size of the words inside the set container, so I first calculate the size of the longest word inside the container and add 10 so the columns don't stick. The current code is this:

#include <set>
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>

void show_columns(const std::set<std::string>& new_words, const std::set<std::string>& old_words) {

  std::string max_str = *std::max_element(new_words.begin(),new_words.end(),[](std::string m1,  std::string m2) {
       return m1.size() < m2.size();
   }); 
   size_t max_size = max_str.size()+10; // +10 para que no se junten (se puede escoger cualquier valor)

    const std::string& m = "New words";
    const std::string& m2 = "Old words";

    std::cout << ' ' << m << std::string(max_size,' ') << m2 << '\n';
    std::cout << ' ' << std::string(m.size(),'-') << std::string(max_size,' ') << std::string(m2.size(),'-') << '\n';

    auto it = new_words.begin();
    for(auto it2 = old_words.begin(); it != new_words.end() || it2 != old_words.end();) {
        if(it != new_words.end()) {
            std::cout << ' ' << *it;
            if(it2 == old_words.end()) {
                std::cout << '\n';
            }
             ++it;
        }
        if(it2 != old_words.end()) {
            std::cout << std::string(max_size,' ') << std::left << *it2 << '\n';
             ++it2;
        }
    }
    std::cout << '\n';   
}

int main() {
    std::set<std::string> new_words{"blue","white"};
    std::set<std::string> old_words{"yellow","orange","black"};
    show_columns(new_words,old_words);

    return EXIT_SUCCESS;
}

The output of the program is:

 New words               Old words
 ---------               ---------
 blue               black
 white               orange
               yellow

The output I expected:

 New words               Old words
 ---------               ---------
 blue                    black
 white                   orange
                         yellow

Aucun commentaire:

Enregistrer un commentaire