C++ 01 Feb 2010 15:32:18

Snippet: Dynamic Box of Strings

//tinodidriksen.com/uploads/code/cpp/dynamic-string-box.cpp

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

int main() {
    std
::vector<std::string> strs;
    strs
.push_back("Hello World!");
    strs
.push_back("This is a text line.");
    strs
.push_back("Shorter line.");

    size_t maxl
= 0;
   
for (size_t i = 0 ; i<strs.size() ; ++i) {
        maxl
= std::max(maxl, strs[i].length());
   
}

    std
::cout << std::string(maxl+4, '*') << std::endl;
   
for (size_t i = 0 ; i<strs.size() ; ++i) {
        std
::cout << "* "
           
<< strs[i]
           
<< std::string(maxl-strs[i].length()+1, ' ')
           
<< "*" << std::endl;
   
}
    std
::cout << std::string(maxl+4, '*') << std::endl;
}

Subscribe to the comments through RSS Feed

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image