开发者

How to change text output depending on the value of x

开发者 https://www.devze.com 2023-02-18 06:51 出处:网络
I want to create a list from one to ten. Each time it loops it adds开发者_开发问答 one to x, I also want it to print like this.

I want to create a list from one to ten. Each time it loops it adds开发者_开发问答 one to x, I also want it to print like this.

1
 2
  3
   4
    5
     6
      7
       8
        9
         10

Right now it prints like this:

1
2
3
4
5
6
7
8
9
10


pseudocode:

for (i: 1..10)
   for(j:1..i) //or for(j:1..(i-1)) if you want zero spaces on line 1
      print space
   print i
   print newline

hth


std::string has a constructor that takes a number and a character, that you can use to generate "x space characters":

#include <iostream>
#include <string>

int main()
{
    for (int x = 0; x < 10; x++) {
        std::cout << std::string(x, ' ') << (x+1) << '\n';
    }
}

Hope that helps.


Hm, you can make a "spacer"-string in the loop and add a space to it everytime it runs through. Then you output the spacer-string + the number of loops.


You could add a parameter to your function that represents the indention level (as a string made of spaces for example), and every time it's called you increase it by one " ".

in a loop you can make the same thing, by just adding one space per increase in your value


char buf[64];
for(int i = 1; i <= 10; i++)
{
  sprintf(buf, "%%%dd\n", i + i / 10 + 1);
  printf(buf, i);
}

or

for(int i = 1; i <= 10; i++)
{
  for(int j = 0; j < i - 1; j++)
    std::cout << ' ';
  std::cout << i << std::endl;
}
0

精彩评论

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