Hi guys,
I made-up this program with no intended purpose. However, I noticed that setting a band width (setw(2)) doesn't work with functions. Any idea why this happen. I attached the output at the end of the code.
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
int mydigit(long);
int main()
{
long num = 7658902; //this is a program I made-up but it is so simple
cout << "The required digit is" << setw(2) << mydigit(num) << endl;
system ("pause");
}
int mydigit (long n)
{
constint ten = 10;
int d = 100;
do
{
if (n % ten > d)
d = n % ten;
n = n/ten;
} while (n != 0);
return d;
}
“doesn't work” isn’t a good description of an issue. You should think in terms of expected behaviour (I’m trying to achieve this...) and resulting behaviour (...but I receive this).
Manages the minimum number of characters to generate on certain output operations and the maximum number of characters to generate on certain output operations.
[...] Notes
The exact effects this modifier has on the input and output vary between the individual I/O functions and are described at each operator<< and operator>> overload page individually.
Stage 3: padding
[...]
If str.width() is non-zero (e.g. std::setw was just used) and the number of CharT's after Stage 2 is less than str.width(), then copies of the fill character are inserted at the position indicated by padding to bring the length of the sequence to str.width().
But it doesn’t say it trims anything.
Anyway, could you please clarify what your code should do? I suspect it doesn’t do what you would like it to do:
#include <iomanip>
#include <iostream>
int mydigit(long);
int main()
{
long num = 7658902;
int myd = mydigit(num);
std::cout << "The required digit is " << std::setw(2) << myd
<< " and std::setw(2) << 200 display "
<< std::setw(2) << 200 << '\n';
}
int mydigit (long n)
{
constint ten = 10;
int d = 100;
std::cout << "\nn: " << n << "; d: " << d << '\n';
do {
std::cout << "n: " << std::setw(7) << n
<< "; n % 10: " << n % ten
<< "; d: " << d
<< "; " << std::setw(7) << n << " % 10 is "
<< ( n % ten > d ? "greater" : "not greater" )
<< " than " << d << '\n';
if (n % ten > d) { d = n % ten; }
n = n/ten;
} while (n != 0);
return d;
}
Output:
n: 7658902; d: 100
n: 7658902; n % 10: 2; d: 100; 7658902 % 10 is not greater than 100
n: 765890; n % 10: 0; d: 100; 765890 % 10 is not greater than 100
n: 76589; n % 10: 9; d: 100; 76589 % 10 is not greater than 100
n: 7658; n % 10: 8; d: 100; 7658 % 10 is not greater than 100
n: 765; n % 10: 5; d: 100; 765 % 10 is not greater than 100
n: 76; n % 10: 6; d: 100; 76 % 10 is not greater than 100
n: 7; n % 10: 7; d: 100; 7 % 10 is not greater than 100
The required digit is 100 and std::setw(2) << 200 display 200