Can't use printf, have to use cout?

Dec 27, 2010 at 7:16am
Why can't I store text in a string and use printf() to output whatever is stored in there?
I'm only doing this, because I'm trying to pass strings to another function, and printf doesn't let me output strings. Not even simple strings like "Hello world"

cout works just fine though, but aparently uses more system resources than printf() does.
What should I do?

Does not work
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main()
{
	string tempText;

	tempText = "\nMenu:\n  n - New Game\n  l - Load Game\n  o - Options\n  c - Credits\n  q - Quit\n\n";
	printf("", tempText);
}


Works as expected.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main()
{
	string tempText;

	tempText = "\nMenu:\n  n - New Game\n  l - Load Game\n  o - Options\n  c - Credits\n  q - Quit\n\n";
	cout << tempText;
}
Last edited on Dec 27, 2010 at 7:42am
Dec 27, 2010 at 7:28am
Printf uses a format string, and takes a c string as an argument.
printf("%s", tempText.c_str);
Last edited on Dec 27, 2010 at 7:30am
Dec 27, 2010 at 7:37am
I tried doing what you suggested and got this error on output

1>.\Game.cpp(81) : error C3867: 'std::basic_string<_Elem,_Traits,_Ax>::c_str': function call missing argument list; use '&std::basic_string<_Elem,_Traits,_Ax>::c_str' to create a pointer to member
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>,
1>            _Ax=std::allocator<char>
1>        ]


EDIT: apologies, I didn't realise .c_str was a function and needed parenthesis, thanks a lot rocketboy.
Last edited on Dec 27, 2010 at 7:53am
Dec 27, 2010 at 7:57am
Should be like this:
printf("%s", tempText.c_str());
Dec 27, 2010 at 7:25pm
whoops, I have a hard time remembering which things are functions and which variables.
Dec 27, 2010 at 7:59pm
You need to #include <cstdio> to use printf() by the way.

Also, don't worry about the speed of printf() vs. that of std::cout. If there is a difference, it will be small, and not worth sacrificing the extra safety that using C++ strings over C strings gets you. Also, printf() is not typesafe.
Last edited on Dec 27, 2010 at 8:02pm
Dec 28, 2010 at 4:18am
Topic archived. No new replies allowed.