0

So this is my code

string name;
cout <<"\n   Enter Your name : \n";
cin >> name;
printf("%s" , name);

and for some weird reasons codeblocks crashes at this

why ?

also how could I fix it ?

thanks

2
  • 2
    Don't mix std::cout with printf. Both are buffered, but uses different buffers, which may make your output unexpected. Commented Feb 21, 2014 at 20:10
  • Mixing C++-style and C-style I/O is perfectly well-defined as long as you have't called ios::sync_with_stdio(false). It may be bad style, though. Commented Feb 21, 2014 at 20:18

2 Answers 2

3

You should compile with all warnings (e.g. g++ -Wall). You'll get a useful warning. You want to use c_str like this

printf("%s", name.c_str());

BTW, why use printfand why do you forget a \n at the end of the printf format string? (or use fflush)

Better code:

cout << name << endl;
Sign up to request clarification or add additional context in comments.

1 Comment

thank you ! I was testing printf , this was just a small part of the code I want to make a text based rpg & I feel printf would take less space without all those "<<" used in cout
2

If you need to pass your std::string to a function that accepts / uses C-style strings (const char *) for input, use .c_str(). It returns a const char *.

This is what you should do when needing to work with existing libraries, system calls, etc. For your own code, it is usually better to find a more C++ way of doing it.

In this case:

std::cout << name << std::endl;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.