1

I want the output to say what arrow key the user pressed. The output I get is:

"You pressed the Dz↕ button."

What I wrote was:

unsigned int key;
string K;
do
{
    key = getch();
    if (key==72)
        K=" up";
    else if(key==80)
        K="down";
    else if (key==77)
        K="right";
    else if (key==75)
        K="left";
    else
        {}
    if (key!=224)
        printf("You pressed the %s button.\n", K);
    else
        {}
}while(key !='q');

return;
kommihe
  • 441
  • 2
  • 6
  • 11

4 Answers4

6

should do std::cout << "You have pressed " << K << " button." << std::endl; You have mixed string object type with printf. printf only accepts a char * or char [] with the %s format string.

Or you might want to access the c string associated with the string object with K.c_str ()

printf ("\ntest %s", K.c_str ());

phoxis
  • 60,131
  • 14
  • 81
  • 117
  • thanks for pointing out, i am a c programmer so it is a habit. – phoxis Jun 16 '11 at 16:59
  • In general, the C++ Standard Library is preferable to C runtime (CRT). There's a way to do all the things you are used to, usually (but not always) elegant. For advanced usage and to amaze and impress your friends, check out http://www.boost.org :-) – Steve Townsend Jun 16 '11 at 17:00
  • @Steve Townsend: You should only use `std::endl` if you want output to be flushed. :) – greyfade Jun 16 '11 at 17:57
  • @greyfade - did not know that, thanks. See here: http://stackoverflow.com/questions/213907/c-stdendl-vs-n – Steve Townsend Jun 16 '11 at 18:05
4

printf is not type-safe, if you pass it mismatched input it is prone to misbehave randomly. Try

printf("You pressed the %s button.\n", K.c_str()); 

Better still, in C++ use operator<< as noted in the other answer.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
0

You print out K, but in case it was not one of the arrows pressed, you don't initialize K. Assign K=key before the if statements.

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
0

printf needs a char* not a std::string try with

printf("You pressed the %s button.\n", K.c_str());
t00ny
  • 1,598
  • 1
  • 11
  • 8