开发者

Formatting C++ output problem

开发者 https://www.devze.com 2023-04-06 10:59 出处:网络
Let me examplify my problem , I\'ve a function like: void printer(int width, int hight){ for(int i=0;i<width;++i) std::cout<<\" & \";

Let me examplify my problem , I've a function like:

void printer(int width, int hight){
    for(int i=0;i<width;++i) std::cout<<" & ";
    for(int i=0;i<hight;++i) std::cout<<" ^ ";
    std::cout<<std::endl;
}

my problem is function printer should always output of bo开发者_开发百科th for loop in same width

e.g: output could look (width 5):

   &^
 &&&^

or there is anyway that i print any of (from above code) for loop's output in constant width independent of no of times for loop executes


Question is unclear. Are you looking for something like the following ?

void printer(int amps, int carets, int overallWidth){
    for (int i = amps + carets; i < overallWidth; i++)  std::cout<<" ";  // leading padding
    for (int i=0;i<amps;++i) std::cout<<"&";
    for (int i=0;i<carets;++i) std::cout<<"^";
    std::cout<<std::endl;
}

The change was just to add a loop for outputting the padding. (also changed the parameters name for clarity)

printer(1,1,5);
printer(3,1,5);

would then produce the output shown in example

   &^
 &&&^

and of course, rather than being passed as a parameter, the overallWidth variable could be hardcoded; an implicit constant of the printer() function.

Edit:
The snippet above stayed very close to that of the question. There are however more idiomatic approaches, for example the following "one liner", which uses one of the string constructor overloads to produce the strings of repeated characters, and iomanip's setw() to produce the padding.

void printer(int amps, int carets, int overallWidth){
   std::cout << setiosflags(ios::right) << setw(overalWidth) 
             << string(amps, '&') + string (carets, '^')
             << std::endl;
}


Look into <iomanip>. Using cout you can specify a width.

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
   cout << setiosflags(ios::left) << setw(10) << "Hello"
        << setiosflags(ios::right) << setw(20) << "World!";

   return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消