setw() zigzag

Sep 20, 2010 at 3:28am
The problem I'm having involves the field width of setw(). My assignment requires me to give an integer output and a millisecond output to control the speed which the characters are drawn. If the int output = 5, and the millisecond output = 50000, the program should display and infinitely loop:

setw(1)*
setw(2)*
setw(3)*
setw(4)*
setw(5)*
setw(4)*
setw(3)*
setw(2)*
setw(1)*

(minus the setw, the asterisks should zigzag from left to right)

My problem is that I cannot get the field width to go any higher than 1 and I cannot get it to display an '*' even with the use of an insertion operator. I'm having no problems with infinite looping but my program displays:

hello
hello
hello
hello
hello
(repeat)


Here is my code:

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

int main(void)
{
auto int fWidth;
auto int time;
auto char n = fWidth;

cout << "Please enter the maximum field width: " ;
cin >> fWidth;
cout << "Enter the microseconds to pause between asterisks: ";
cin >> time;

while ((n = 1) && (n <= fWidth))
{
cout << setw(n) << "hello" << endl;
}
return 0;
}

Any help would be appreciated.

Thanks,
Brian
Sep 20, 2010 at 5:50am
closed account (D80DSL3A)
The value of n is always = 1 within your while loop. The (n = 1) expression is assigning n = 1 and then nothing else changes its value.
This code should at least get n to increase from 1 to fWidth, building one edge of a tooth:
1
2
3
4
5
6
n = 1;
while( n <= fWidth )
{
    cout << setw(n) << "hello" << endl;
    n++;// increments n by 1
}

If you want an "*" to appear instead of "Hello" then replace "Hello" with "*"
To get the tooth to ramp up and down repeatedly I think the following would work.
1
2
3
4
5
6
7
8
while( 1 )// loop forever. User will terminate app.
{
    for( n = 1; n <= fWidth; n++ )// n goes up
        cout << setw(n) << "*" << endl;

    for( n = fWidth; n >= 1; n-- )// n comes down
        cout << setw(n) << "*" << endl;
}

Please let me know if this code works. I haven't actually tested it.
By the way. There is no speed set for the printing rate here. The program will simply print as fast as it can.
Sep 20, 2010 at 6:01am
Also, you should remove the auto keywords.
auto is deprecated and it has always been completely pointless to specify it explicitly.
Topic archived. No new replies allowed.