M
Mark
Gavin said:Mark said:well, ok, i could use std::strings, but printf won't accept them, so i
have to convert them where ever i want to use them, right?
Not if you do you input and output using streams (like cin and cout) -
see below.
i've always tried to advoid std:strings and other libraries i didn't
program myself... always thinking there is too much baggage, or they
aren't compatible with other functions and such.
The facilities of the C++ standard library (strings, streams,
containers, algorithms, etc.) are fully compatible with each other by
design and provide commonly needed functionality out of the box.
running this quick test,
#include <cstdlib>
#include <iostream>
using namespace std;
char * itoa(int i)
{
static char buff[35];
return _itoa(i,buff,10);
}
int main(int argc, char *argv[])
{
printf("%s %s %s", itoa(1), itoa(2), itoa(3));
system("PAUSE");
return EXIT_SUCCESS;
}
it prints "1 1 1"
now if i'm not mistaken, since the buffer is in the same memory
location each time the function is called (because it's static)... all
3 pointers should point to the same location in memory, which is
probably why they are printing the same thing.
now what i'm thinking really happens, is that itoa is called 3 times,
the pointers are returned, and THEN the "%s %s %s" is evaluated, using
what happens to be the same pointer, rather than evaluating each %s and
corresponding parameter at the same time....
which all makes very good sense to me now. i feel clever for figuring
that out .. i hope i'm right![]()
Yes you are right. All the arguments to a function are fully evaluated
_before_ the function itself is called. Parsing "%s %s %s" and
inserting the character sequences obtained by dereferencing the pointer
arguments happens _inside_ the printf function, so by the time it
happens, the three itoa calls are complete.
So what actually gets printed is whatever was stored in the buffer by
the last of the three calls to itoa. In your case, the last call must
have been itoa(1). That's allowed - the compiler does not have to
evaluate the function arguments in the order they apppear in your code.
It can evaluate them in any order it likes.
are there any other print functions that actually take std:strings as
parameters?
or is there a way i could do "my string" + 5 + my_other_string?
#include <string>
#include <iostream>
int main()
{
std::string my_other_string = "my other string";
std::cout << "my string" << 5 << my_other_string << "\n";
return 0;
}
Gavin Deane
Thanks Gavin
Nice to know some people are a little more polite.