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

Andrew
  • 1
  • 2
    Don't mix `std::cout` with `printf`. Both are buffered, but uses *different* buffers, which may make your output unexpected. – Some programmer dude Feb 21 '14 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. – Brian Bi Feb 21 '14 at 20:18

2 Answers2

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;
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 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 – Andrew Feb 21 '14 at 20:15
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;
crashmstr
  • 28,043
  • 9
  • 61
  • 79