print

could you please remind me how can i print with a specific number of characters.

for example if i say to print 0 to print 000
and if 1 to print 001

and also for strings

thank you
@i9try

I'm sure there are more elegant ways of doing it, but this is how have done it in my programs.

1
2
3
4
5
6
7
8
for (int num = 0; num < 110; num++)
{
	if (num < 100)
		cout << "0";
	if (num < 10)
		cout << "0";
	cout << num << " ";
}


Not sure what you're needing for the strings, so, I'll leave that for another.
closed account (EwCjE3v7)
You can fill in using std::setfill

Here is an example:

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::setfill('0') << std::setw(3) << 1 << std::endl; // prints 001

    return 0;
}



Same for strings:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <iomanip>
#include <string>

int main()
{
    std::string s = "1";

    std::cout << std::setfill('0') << std::setw(3) << s << std::endl; // prints 001

    return 0;
}
Last edited on
PS Note that std::setfill is sticky, but std::setw isn't.

That is, once you've called setfill the new fill char is used until you call it again to change the char; setw must be called before each insertion you need it for.

Also, the side the field is filled is depends on the alignment. So if you call std::left the fill char will be appended rather than prepended. (There is also std::internal which output e.g. -77 as - 77 if filling with spaces.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <iomanip>
#include <string>

int main() {
    const int count = 4;

    std::cout << std::setfill('0'); // sticky, so need to call once here, rather than in loop
    
    for(int i = 0, ID = 1; i < count; ++i) {
        std::cout << "ID = " << std::setw(3) << ID << "\n";
        ID *= 7;
    }
    std::cout  << "\n";

    std::cout << std::setfill('#') << std::left; // new fill, plus align left
    
    for(int i = 0, ID = 1; i < count; ++i) {
        std::cout << "ID= " << std::setw(3) << ID << "\n";
        ID *= 7;
    }
    std::cout << "\n";

    std::cout << std::setfill(' ') << std::right; // new fill, plus align right
    
    for(int i = 0, ID = 1; i < count; ++i) {
        std::cout << "ID = " << std::setw(3) << ID << "\n";
        ID *= 7;
    }
    std::cout << "\n";

    return 0;
}


ID = 001
ID = 007
ID = 049
ID = 343

ID = 1##
ID = 7##
ID = 49#
ID = 343

ID =   1
ID =   7
ID =  49
ID = 343


Actually, setw is the only one of the current set of maniuplators that behaves this way (i.e. is non-sticky.) All the others change the stream's behaviour permanently (well, until the next time they're called) or perform an action (ws, endl, ends, flush.)

Andy

Which iomanip manipulators are 'sticky'?
http://stackoverflow.com/questions/1532640/which-iomanip-manipulators-are-sticky
Last edited on
Topic archived. No new replies allowed.