Mail Archives: djgpp/2000/10/18/18:42:57
Your last message would have bounced, so I'll quote it in full here.
On Tue, 17 Oct 2000 17:13:01 -0700, you wrote:
> #include <iostream>
> #include <iomanip>
> #include <string>
> using namespace std;
>
> int main(void)
> { string car = "Yugo";
> double tank = 6.36, mpg = 36;
>
> cout << setiosflags(ios::fixed);
> cout << "Car Tank MPG Range" << endl;
>
> cout << setiosflags(ios::left) << setw(12) << car //setw() may not
> work
> << setiosflags(ios::right) << setw(7) << setprecision(1) << tank
> << setw(7) << mpg
> << setw(7) << setprecision(0) << tank * mpg << endl;
>
> car = "Rolls Royce\0";
> tank = 35;
> mpg = 11.2;
>
> cout << setiosflags(ios::left) << setw(12) << &car[0] //setw() fix
> << setiosflags(ios::right) << setw(7) << setprecision(1) << tank
> << setw(7) << mpg
> << setw(7) << setprecision(0) << tank * mpg << endl;
>
>
> return 0;
> }
>
>
> Output:
>
> Car Tank MPG Range
> Yugo 6.4 36.0 229
> Rolls Royceion d+ 35.0 11.2 392
>
>
> Analysis: setw() does not actually set the width of the string car =
> "Yugo". The only space between Yugo and the next value is because of
> setw(7) before the value of tank.
>
> The remedy, namely use C style pointers to refer to the string, does not
> work because the string class does not seem to input a \0 character at
> the end of the inputed string.
>
> I would appreciate any feedback as to how I can make the names and
> results line up.
Your original complaint that setw() does not work with C++ strings
appears to be valid.
Since C strings appear to work ok, a suitable workaround would indeed
be to convert the C++ string to a C string as you suggest.
Unfortunately, the method you use to do this won't work. In fact, it
is completely implementation dependent as to what it will do, but I
think we can safely say it doesn't work with gcc (and there is no
reason why it should).
The correct method is to use c_str(), like this:
cout << setiosflags(ios::left) << setw(12) << car.c_str()
Note that setiosflags(ios::left) is itself a workaround because the
'left' manipulator is missing; you should be able to do:
cout << left << setw(12) << car
I posted a fix for this a while back. Search the mail archives for
"left" and "iomanip" if you are interested.
- Raw text -