Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print to output at specific location on line in c++

I am trying to print to a uniform position in a line after printing out a header. here's an example:

PHRASE                 TYPE
"hello there"       => greeting
"yo"                => greeting
"where are you?"    => question
"It's 3:00"         => statement
"Wow!"              => exclamation

Assume each of these are stored in a std::map<string, string>, where key = phrase and value = type. My issue is that simply using tabs is dependent on the console or text editor that I view the output in. If the tab width is too small I won't know for sure where it will be printed. I have tried using setw, but that only prints the separator ("=>") a fixed distance from the end of the phrase. Is there a simple way to do this?

NOTE Assume for now that we just always know that the phrase will not be longer than, say, 16 characters. We don't need to account for what to do if it is.

like image 553
ewok Avatar asked Jan 14 '23 14:01

ewok


1 Answers

Use std::left and std::setw:

std::cout << std::left; // This is "sticky", but setw is not.
std::cout << std::setw(16) << phrase << " => " << type << "\n";

For example:

#include <iostream>
#include <string>
#include <iomanip>
#include <map>

int main()
{
    std::map<std::string, std::string> m;
    m["hello there"]    = "greeting";
    m["where are you?"] = "question";

    std::cout << std::left;

    for (std::map<std::string, std::string>::iterator i = m.begin();
         i != m.end();
         i++)
    {
        std::cout << std::setw(16)
                  << std::string("\"" + i->first + "\"")
                  << " => "
                  << i->second
                  << "\n";
    }
    return 0;
}

Output:

"hello there"    => greeting
"where are you?" => question

See http://ideone.com/JTv6na for demo.

like image 114
hmjd Avatar answered Jan 29 '23 11:01

hmjd