Hello,
I have this code:

#include <iostream>
#include <string>

void main()
{
	 std::string a = "Sample";
	 printf("%s", a);
	 std::cin.get();
}

and it prints some I think random letters. Where i made mistake? And how should i change the code to write "Sample"?

Thanks for answers and sorry for my english

Hello,
I have this code:

#include <iostream>
#include <string>

void main()
{
	 std::string a = "Sample";
	 printf("%s", a);
	 std::cin.get();
}

and it prints some I think random letters. Where i made mistake? And how should i change the code to write "Sample"?

Thanks for answers and sorry for my english

Any specific reason to use printf()? Because you can rather use cout.

why not like this?

#include<iostream.h>
#include<conio.h>
void main()
{
char *a="sample";
cout>>a;
getch();
}

I'm pretty sure "%s" is expecting a C style string, not an STL string object, which is what a is declared to be. Use cout instead of printf() or use a.c_str() instead of a.

Mixing C and C++ I/O methods like printf() and cin in the same program isn't recommended.

And, last, but not least, main() should have return type int, not void, even if your compiler allows you to use void in this setting.

why not like this?

#include<iostream.h>
#include<conio.h>
void main()
{
char *a="sample";
cout>>a;
getch();
}

Yes, just make the following change to your code:

cout<<a;

The operator you used is for cin!

In my program, I am using Allegro and function allegro_draw_textf(),

al_draw_textf(font15, al_map_rgb(200, 200, 200), mouse_position_x + 15, mouse_position_y, ALLEGRO_ALIGN_LEFT, "%s", name);

and I have exactly the same problem there. And I can't use there "cout" I think.

Again, "%s" indicates a C style string. If a is an STL string object then you can use the c_str() method to use a as a C style string.

This article has been dead for over six months. Start a new discussion instead.