Re: Doubles and Integers as strings.
"GeorgeJ" wrote:
As a newbie to C++ I would really benefit from the
suggestions of experienced
programmers as to the best to way to convert numbers into
strings and output
these strings to the console. In the various books I've
managed to get ahold
of, various ways are show...
Console::writeln(f)
This is managed C++ (.NET). `Console::writeln' is not
available for native C++ programs.
printf("This is your number %d",f)
This is most commonly used C-legacy method. A lot of people
like it for its simplicity and straightforwardness.
cout << "This is the number" << f
This is intended C++ method to do output (using streams).
One book suggests avoiding the printf command as it can
lead to a program
crash if the type identifier which comes immedeatly after
% doen not
correspond to the type of the variable f.
The book is right. The main problem of `printf'-like
functions is that you can't ensure a validity of parameters
during compile time. Errors are detected only at run time.
It is because `printf' family of functions accept variable
number of argumets, but no information is given about them.
Arguments are checked when format string is parsed.
Suppose I have
double f1=1.23E2;
Is there a way in C++ of using f1 to produce the following
strings
"12300" "1.23E2" " 12300 "
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double f1 = 1.23E2;
cout << setprecision(2) << fixed << f1 << '\n';
cout << scientific << f1 << '\n';
cout << fixed << ' ' << f1 << ' ' << '\n';
return 0;
}
int i1=123
" 123"
cout << setw(6) << right << i1 << '\n';
I'd sure appreciate it if someone could show me how these
strings might be
produced and output to the console interspersed with text.
You just infuse text with numbers:
cout << "This is the number:"
<< setw(6) << right << i1 << '\n';
For more info about formatting look here:
"Using Insertion Operators and Controlling Format"
http://msdn2.microsoft.com/en-us/library/420970az(VS.80).aspx
Alex