setw Problems?

Mar 22, 2017 at 4:07pm
I have a problem with setw inside my while loop. When I run it, the first 30 loops are fine. On the 31st loop, there is an extra space for no reason. Anyone know why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  while (principal >= principalpaid)  
	{
	  if (month == 1)
	  {
	    cout << setw(19) << "0" << setw(28) << "$ 0.00" << setw(27) << "$ 0.00" << setw(17) << "$ " << principal << endl; 
	  }
	
	  interest2 = principal * interest;
	  principalpaid = payment - interest2;
	  principal = principal - principalpaid;
	  
	  cout << setw(19) << month++ << setw(24) << "$ " << interest2 << setw(21) << "$ " << principalpaid << setw(17) << "$ " << principal << endl;
	  
	}
Mar 22, 2017 at 4:08pm
When I get rid of the dollar sign before principalpaid, principal works fine. When I add the dollar sign in, principal gets a space added to it every thirty loops.
Mar 22, 2017 at 5:50pm
Hello XRayKiller,

I do not have enough information to test the loop, but I am thinking that the "setw()" before principalpaid and principal may be to small. Or you might try putting the "setw()" on the right side of "$ " and see what happens.

Hope that helps,

Andy
Mar 22, 2017 at 6:54pm
setw only applies to the next thing that is outputted. If you want to set the width for both the dollar sign and the value combined I think you will have to first convert them to a string so that you can output them both in one operation.

 
cout << setw(10) << ("$ " + to_string(value)) << endl;
Last edited on Mar 22, 2017 at 6:57pm
Mar 22, 2017 at 8:13pm
Hello XRayKiller,

I do not know if this will work with real numbers, but it should give you a place to start from.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
while (principal >= principalpaid)
{
	std::cout << std::fixed << std::showpoint;
	if (month == 1)
	{
		std::cout << std::setw(19) << "0" << std::setw(31) << "$    0.00" << std::setw(31) << "$     0.00" << std::setw(21) << "$   " << std::setprecision(2) << principal << std::endl;
	}

	interest2 = principal * interest;
	principalpaid = payment - interest2;
	principal = principal - principalpaid;

	std::cout << std::setw(19) << month++ << std::setw(24) << "$ ";
	std::cout << std::setw(9) << std::setprecision(2) << interest2 << std::setw(21) << "$ ";
	std::cout << std::setw(10) << std::setprecision(2) << principalpaid << std::setw(17) << "$ ";
	std::cout << std::setw(10) << std::setprecision(2) << principal << std::endl;
		
	// Original.
	//std::cout << std::setw(19) << month++ << std::setw(25) << "$ " << interest2 << std::setw(21) << "$ " << principalpaid << std::setw(17) << "$ " << principal << std::endl;
}


Hope that helps,

Andy
Topic archived. No new replies allowed.