String Variables With 'Printf'

closed account (D3pGNwbp)
I was wondering how you'd print a string variable with the printf function.
I thought that the code below would work since '%s' is for strings, but it just displays 'Hello, 4 !!'. How can I get it to display 'Hello, Phillip'?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> 
#include <cstdlib>
#include <string>
using namespace std;

int main() 
{
	string yourName = "Phillip";

	printf("Hello, %s", yourName);

	cin.ignore(); cin.get();
	return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream> 
#include <cstdio>
#include <string>

using namespace std;

int main() 
{
	string yourName = "Phillip";

	printf("Hello, %s", yourName.c_str());

	cin.ignore(); cin.get();
	return 0;
}


C standard functions as printf know nothing about C++ classes including std::string.
Last edited on
closed account (D3pGNwbp)
Thank you very much!
Last edited on
Topic archived. No new replies allowed.