Where can I insert this break function?

Where can insert the following break function into this body of code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
char thing; 

cin >> thing; 
if (thing == 'a') 
{ 
break; 
}

  do { 
printf ("Guess the number (1 to 100): "); 
scanf ("%d",&RGuess); 
if (RNum<RGuess) puts ("try again"); 
else if (RNum>RGuess) puts ("try again"); 
} while (RNum!=RGuess); 

puts ("Congratulations!"); 
return 0; 
} 
I have to sat I don't understand your question... You already have a do-while so you exit from the cycle when RGuess is equal to RNum. Why do you want to use break? Can you explain your problem a little bit better?
Basically I want to add a key press function , quitting the program when 'a' is pressed. So the user can either make a guess or quite the game without guessing by pressing 'a'.
Last edited on
Put it right after the scanf(), like this:

1
2
3
4
5
6
7
8
9



scanf( %d", &RGuess );

if( "a" == RGuess )
    break;

 


Last edited on
You can't ask for an integer and and a character at the same time unless you make everything strings and then do string -> number conversions.

It would be much easier if you made the sentinel value -1 instead of a character.
Then, inside your loop, you can have
1
2
3
4
if (RGuess == -1)
    break;
else if (RNum < RGuess)
    // ... etc 


May I ask why you're mixing C++'s "cin >>" with C's scanf() function? Also, if you do want to see a way in C++ of being able to ask for both a character and a number at the same time, I can show one using std::stringstream.

koothkeeper, I don't think your function would work since you're trying to compare a c-string literal to an int.

Last edited on
1
2
3
4
if (thing == 'a') 
{ 
return 0;
}

this will be the best to stop the program if the user pressed a
@Ganado, you're right! I haven't used scanf() in 25 years. I forgot that if the input doesn't match one of the formatting characters, scanf can return an error. In this case, since we're using '%d', putting a 'q' in causes scanf() return zero, and scanf() becomes unusable, at least on my system.

You're right about mixing C++ and C: 'tain't neat! This is much easier with the functions and libraries offered to us with C++.
Topic archived. No new replies allowed.