Using setw and setfill

For a homework problem, I am supposed to code a program, outputting the title with a line of asterisks under it, like this:

Area of a circle program by Josh Hicks
**************************************


(Note: The asterisks are supposed to line up evenly with the text; on here they don't)

The "Area of a circle program by Josh Hicks" is 38 characters so I thought if I wrote

cout << "Area of a circle program by Josh Hicks\n";
cout << setw(38) << setfill('*');


that it would look like the above, but it comes out something like this:

Area of a circle program by Josh Hicks
******************


If I code the following

cout << "Area of a circle program by Josh Hicks\n";
cout << setw(58) << setfill('*');


changing the setw(38) to setw(58), it comes out properly.

Can anyone tell me why that is? (I'm using Dev-C++ 4.9.9.2)
Well, letters have its own length..

for example
the length of letter W compared to letter l is much longer
and for * (asterisk) it has a fixed length
so length of * compared to letter l is longer...

So it means that you can't assign equal number of asterisk to the number of letters
Hmm...

possible solution is, if your using console...

I think you can use SetConsoleCursorPosition() in outputting the text and the asterisk.

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


void gotoxy(char passtext)
{
        int i, j;
	HANDLE hOut;
	COORD Position;
	CONSOLE_CURSOR_INFO info;
	hOut = GetStdHandle(STD_OUTPUT_HANDLE);
        for(i = 0; i < 39; i++){
	    Position.X = i; //set the position of x
	    Position.Y = 3; //set the position of y
	    SetConsoleCursorPosition(hOut, Position);
	    cout<<passtext[i];
        }
        for(j = 0; j < 39; j++){
	    Position.X = j; //set the position of x
	    Position.Y = 4; //set the position of y
	    SetConsoleCursorPosition(hOut, Position);
	    cout<<"*";
        }         
}

int main(){

    char text[39] = {"Area of a circle program by Josh Hicks"};
    gotoxy(text);

    return 0;
}


be sure to include windows.h
Last edited on
Topic archived. No new replies allowed.