Hi,
First,let me mention that I am coming back to C++ from Java, which has a printf() method that is very easy to use compared to what I've seen from C++'s cout and printf().
I am getting very frustrated with trying to display a simple C++ string, not a C string, not a char array.
I can do it easily using cout and #include<string> as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
#include <string>
using namespace std;
void main()
{
string hello = "HELLO!";
cout << hello << endl;
cout << endl;
cout << "Press any key to exit.";
cin.get();
}
|
However, I find cout cumbersome and would love to use printf() instead.
I have no trouble using printf() to display an int:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <string>
using namespace std;
void main()
{
/*
string hello = "HELLO!";
cout << hello << endl;
*/
int age = 21;
printf("you are %d years old\n", age);
cout << endl;
cout << "Press any key to exit.";
cin.get();
}
|
However, printf() will not display a string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
#include <string>
using namespace std;
void main()
{
string hello = "HELLO!";
/*
cout << hello << endl;
int age = 21;
printf("you are %d years old\n", age);
*/
printf("%s", hello);
cout << endl;
cout << "Press any key to exit.";
cin.get();
}
|
This display garbage.
I UNDERSTAND THAT %s IS THE SPECIFIER FOR "String of characters" AND THAT C++ APPARENTLY HAS NO SPECIFIER FOR string. I have found some examples that turn a string into a char array so that %s will work.
MY QUESTION IS: why isn't there a nice simple way to display a C++ string, using printf() and can someone show me the easiest way to do it?