Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to right justify multiple pieces of data

Tags:

c++

justify

So I have to send to std::cout a column of data where I have to also display some characters around the data like:

    Plot Points
   (0,0), (2,3) 
(1,10), (12,14)

where I have to right justify the last right parenthesis under the letter "s" in "Points" in the column header.

I am putting the data out like:

cout << right << setw(12) << "(" << x1 << "," << y1 << "), (" << x2 << "," << y2 << ")";

But all the examples I have seen seem to show that the right and setw only seem to affect the next piece of data I send to cout, so in this case the "(" only.

Is there any way to group all those characters and variables together to have them all justified together in the column of output?

I'm just learning C++ so expect there is some simple solution I haven't learned yet?

like image 263
James Kunz Avatar asked Nov 20 '16 17:11

James Kunz


1 Answers

Is there any way to group all those characters and variables together to have them all justified together in the column of output?

Yes, you can use a little helper function to build a string:

std::string parentized_pair(int x, int y) {
    std::ostringstream oss;
    oss << "(" << x "," << y << ")";
    return oss.str();
}

and use that one in the final output:

cout << right << setw(12) << parentized_pair(x1,y1) 
     << right << setw(12) << parentized_pair(x2,y2);
like image 116
πάντα ῥεῖ Avatar answered Nov 15 '22 07:11

πάντα ῥεῖ