String Variables With 'Printf'
Apr 28, 2013 at 10:49pm UTC
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;
}
Apr 28, 2013 at 10:56pm UTC
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 Apr 28, 2013 at 10:56pm UTC
Apr 28, 2013 at 11:00pm UTC
Thank you very much!
Last edited on Apr 28, 2013 at 11:00pm UTC
Topic archived. No new replies allowed.