From: Jason Green To: Eric Nute Cc: djgpp AT delorie DOT com Subject: Re: Problems with strings while using djgpp Date: Wed, 18 Oct 2000 23:40:54 +0100 Message-ID: References: <39EB742E DOT 28DBB7BB AT iprg DOT nokia DOT com> <39ECEB0D DOT E1D1E601 AT iprg DOT nokia DOT com> In-Reply-To: <39ECEB0D.E1D1E601@iprg.nokia.com> X-Mailer: Forte Agent 1.7/32.534 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 8bit X-MIME-Autoconverted: from quoted-printable to 8bit by delorie.com id SAA20742 Reply-To: djgpp AT delorie DOT com 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 > #include > #include > 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.