440,417 Members | 1,856 Online
Need help? Post your question and get tips & solutions from a community of 440,417 IT Pros & Developers. It's quick & easy.

# A small game

 P: n/a My friend sent me the prototype of a game written in C++ and asked for advice: IDEA: Game will ask the user to thin of a number. User will press a keystroke after he has thought of a number. Then program will ask him to do some little arithmetic and will finally ask for the result. It will then print what user has thought of. Here is what I finished with. Any advice is appreciated :) #include int main() { const int think_time = 5; std::cout << std::endl; std::cout << "<<<<<<< Let's play a Game >>>>>>\n" << std::endl; std::cout << "\tThink of a number between 1 to 9\n" << "\tPress Ctrl-D when you are done"; char ch; while( std::cin >ch ) { continue; } std::cout << std::endl << std::endl; std::cout << "\t*Add 10 to that number\n"; sleep(think_time); std::cout << "\t*Now subtract 5 from it\n"; sleep(think_time); std::cout << "\t*Add another 20 to it\n"; sleep(think_time); std::cout << "\t*Subtract 7 from it\n"; sleep(think_time); std::cout << "\t*Subtract 3 from it\n"; sleep(think_time); std::cin.clear(); std::cout <<"\tHow Much U Have Now :- "; int think_num; std::cin >think_num; int result = think_num - 15; if(result < 0) { result = -(result); } std::cout <<".....Number you thought is :- " << result << std::endl; return 0; } -- www.lispmachine.wordpress.com my email is @ the above blog. Google Groups is Blocked. Reason: Excessive Spamming Sep 16 '08 #1
23 Replies

 P: n/a On Sep 16, 10:12*am, arnuld int main() { * const int think_time = 5; * std::cout << std::endl; * std::cout << "<<<<<<< Let's play a Game >>>>>>\n" << std::endl; * std::cout << "\tThink of a number between 1 to 9\n" * * * * * * << "\tPress Ctrl-D when you are done"; * char ch; * while( std::cin >ch ) * * { * * * * * continue; * * } * std::cout << std::endl << std::endl; * std::cout << "\t*Add 10 to that number\n"; * sleep(think_time); * std::cout << "\t*Now subtract 5 from it\n"; * sleep(think_time); * std::cout << "\t*Add another 20 to it\n"; * sleep(think_time); * std::cout << "\t*Subtract 7 from it\n"; * sleep(think_time); * std::cout << "\t*Subtract 3 from it\n"; * sleep(think_time); * std::cin.clear(); * std::cout <<"\tHow Much U Have Now :- "; * int think_num; * std::cin >think_num; * int result = think_num - 15; * if(result < 0) * * { * * * result = *-(result); * * } * std::cout <<".....Number you thought is :- " * * * * * * << result * * * * * * << std::endl; * return 0; } --www.lispmachine.wordpress.com my email is @ the above blog. Google Groups is Blocked. Reason: Excessive Spamming Hi Arnuld It is a simple program that exercises about I/O streams, input loop, and simple arithmetic. Here are few simple things: 1. It is assumed program is running under Unix environment. Use Ctrl+D/Ctrl+Z in your message: 2. Include the interface header file for "sleep" function. 3. Use a function like Abs for the following code: if(result < 0) { result = -(result); } int abs(int a) { return a 0 ? a : -a; } Good luck Saeed Amrollahi Sep 16 '08 #2

 P: n/a On Sep 16, 4:12 pm, arnuld

 P: n/a On Sep 17, 4:01 am, tony_in_da...@yahoo.co.uk wrote: On Sep 16, 4:12 pm, arnuld

 P: n/a In article , 3. Use a function like Abs for the following code: if(result < 0) { result = -(result); } int abs(int a) { return a 0 ? a : -a; } #include result = std::abs(result); Sep 17 '08 #5

 P: n/a James Kanze wrote: You should use endl until you understand buffering issues. Given the level of the posting, he's far from that yet. I find that a bit contradictory with what you wrote immediately after: Also, by default, std::cin and std::cout are tied, so any attempt to read on std::cin will flush the buffer on std::cout. Given that the most usual reason for flushing std::cout is so that the text will be displayed before the user is asked for some input with std::cin, and given that, as you say, std::cout *is* automatically flushed when std::cin is used, there doesn't seem to be too many reasons to use std::endl. The biggest problem with std::endl is precisely that it flushes the output stream. If a new user is taught that std::endl is good and should always be used by default, he will learn that bad habit, and it will carry on a long time. At some point he will start creating programs which write enormous amounts of (text) data to an output file, and by custom he will use std::endl to write newlines to it. If these newlines are very common in this output, in most systems the writing will be slowed down by a rather big factor. He might not even realize that something is wrong, and could think that that writing speed is normal when in fact it's completely hindered by the constant needless flushing. IMO the difference between "\n" and std::endl can and should be taught from the very beginning, and the recommendation given that "\n" should be used by default. Just say something like "if at some point you are outputting some text with std::cout and then your program pauses or whatever and the text is not appearing on screen, output an std::endl or std::flush to force it to show the text". Also when creating CLI applications which might require showing some progress percentage, this "trick" is useful: std::cout << "\rProgress: " << percentage << "%" << std::flush; Sep 17 '08 #6

 P: n/a On Sep 17, 2:31 pm, Juha Nieminen

 P: n/a On Wed, 17 Sep 2008 13:38:24 -0700, James Kanze wrote: I know that the difference exists, but I've never encountered a case where it was significant. At any rate, it's a performance issue, only to be addressed once the program actually works. For beginners, it is absolutely essential that what they've written be output, so that they don't get confused when debugging. And even for experienced programmers, if the program crashes, it's a lot easier to figure out what went wrong if the data you wrote actually made it to the disk. For the most part I agree with you. Generally, if I have a performance critical application (numeric integration say, or and FDTD loop), I'll pull the output somewhere outside the loop so I'm not writing output every small step. If I do need output somewhere where the performance hit from buffer flushing is critical, it's usually because I'm debugging, and so I'm more concerned with reliable and complete output than with efficiency. In defense of the parent however, there exist problem domains where these arguments don't hold. I also encounter them from time to time. An example is outputting largeish matrices. These kind of judgements often depend heavily on what kind of coding you do. Sep 17 '08 #8

 P: n/a James Kanze wrote: That's simply not true. Except for small, Unix type filter programs, I don't think I've ever output where there wasn't a need to flush. It's the rule, rather than the exception. You have never written a program which opens a file for writing, writes a bunch of data to it, and then closes the file? Do you mean you always keep files open for the entire execution of the program? I don't believe that. Sep 17 '08 #9

 P: n/a On Sep 17, 11:32 pm, James Kanze

 P: n/a On Sep 18, 12:38 am, glen stark

 P: n/a On Sep 18, 1:46 am, Juha Nieminen

 P: n/a On Sep 18, 3:48 am, tony_in_da...@yahoo.co.uk wrote: On Sep 17, 11:32 pm, James Kanze

 P: n/a James Kanze wrote: > You have never written a program which opens a file for writing,writes a bunch of data to it, and then closes the file? Sure. So you are admitting here that you have written such programs. >Do you mean you always keep files open for the entireexecution of the program? It depends on the program, but most of the time, yes. And here you admit that at least *sometimes* you don't keep files open for the entire execution of the program. > I don't believe that. And yet, it's true. And here you deny both of your own admissions you just made above. You are not writing very consistently. (Yes, I know I'm nitpicking, and I understand what you really meant. No need to sweat over it.) Sep 18 '08 #14

 P: n/a James Kanze wrote: There is no "line oriented" (I think you mean line buffered) output in C++. std::cerr is "unit buffered", which means that output is flushed after each operation (each << operator). Actually I remember I tested this once, and at least with gcc std::cerr flushes after each written *character*. (I have to admit, though, that this was a long time ago and I haven't tested this recently, and I don't know if it has been changed. In a way it doesn't makes sense, because if you are outputting eg. the value of an integer variable which has several digits, and the program is forcefully terminated in the middle of printing that value, the output will have the first digits of the number but not the last ones, which can make the output misleading and confusing.) Sep 18 '08 #15

 P: n/a On Sep 18, 5:49 pm, James Kanze

 P: n/a On Wed, 17 Sep 2008 09:39:42 +0200, Michael DOUBEZ wrote: I guess it is a metter of taset but in this case, I prefer iterating on the content of a table: static char const* const instructions[]= {"Add 10 to that number" ,"Now subtract 5 from it" ,"Add another 20 to it" ,"Subtract 7 from it" ,"Subtract 3 from it" ,NULL //end table with NULL }; for(const char* it=instructions;*it;++it) { std::cout << "\t*"<<*it<<"\n"; sleep(think_time); } Looks okay to me but why use "static" in the array definition ? clear cin Just before reading it. I did, check again. Check the operation succeeds and offer a way to stop the program: while (!(std::cin >think_num)) { if(std::cin.eof()) { std::cout<<"Tired of playing ?\nBye"<::max(), '\n'); } okay, will put it in a separate function taking an "int&" argument, I don't want to mess with main() all the time. If result is negative, the player lied or made a mistake. yes, he did :) So better not to provide answer if result is invalid. const int result = think_num - 15; if((result >= 1) && (result <= 9)) { std::cout <<".....Number you thought is :- " << result << std::endl; } else { std::cout <<"Really ? How odd !"<

 P: n/a On Sep 19, 4:26 pm, arnuld #include int get_number(); int main() { const int think_time = 5; std::cout << "\n\n<<<<<<< Let's play a Game >>>>>>\n\n"; std::cout << "Think of a number between 1 to 9.\n" << "Press 'Enter' when you are done: "; char ch; std::cin.clear(); Won't need this unless recovering from bad input, and you haven't seen any yet.... while( std::cin >ch ) { if( ch != '\n') { continue; } else { break; } } You could simplify this to: while (std::cin >ch && ch != '\n') /* do nothing */; or if that's uncomfortable (it's called "short-circuit boolean evaluation" - takes a bit of getting used to ;-) ) while (std::cin >ch) if (ch == '\n') break; > std::cout << "\n\n" << "\t*Add 10 to that number\n"; sleep(think_time); std::cout << "\t*Now subtract 5 from it\n"; sleep(think_time); std::cout << "\t*Add another 20 to it\n"; sleep(think_time); std::cout << "\t*Subtract 7 from it\n"; sleep(think_time); std::cout << "\t*Subtract 3 from it\n"; sleep(think_time); std::cout <<"\tHow Much U Have Now :- "; int think_num = get_number(); int result = think_num - 15; if((result >= 1) && (result <= 9)) { std::cout <<".....Number you thought is :- " << result << "\n\n its Magic! ;)\n" << std::endl; } else { std::cout <<"Really ? How odd !"<num)) { if(std::cin.eof()) { std::cout<<"Tired of playing ?\nBye\n"<::max(), '\n'); } return num; } --www.lispmachine.wordpress.com my email is @ the above blog. Google Groups is Blocked. Reason: Excessive Spamming Sep 19 '08 #19

 P: n/a On Sep 18, 3:32 pm, Juha Nieminen

 P: n/a On Sep 18, 3:37 pm, Juha Nieminen

 P: n/a On Sep 19, 10:29 am, tony_in_da...@yahoo.co.uk wrote: On Sep 19, 4:26 pm, arnuld ch ) { if( ch != '\n') { continue; } else { break; } } You could simplify this to: while (std::cin >ch && ch != '\n') /* do nothing */; or if that's uncomfortable (it's called "short-circuit boolean evaluation" - takes a bit of getting used to ;-) ) while (std::cin >ch) if (ch == '\n') break; The short-circuit evaluation is far clearer. In general, it's best to avoid break or continue in a loop. In this case, of course, he could simplify even more by using istream::ignore. -- James Kanze (GABI Software) email:ja*********@gmail.com Conseils en informatique orientée objet/ Beratung in objektorientierter Datenverarbeitung 9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34 Sep 19 '08 #22

 P: n/a In article <48********@news.bluewin.ch>, glen stark On Wed, 17 Sep 2008 13:38:24 -0700, James Kanze wrote:In defense of the parent however, there exist problem domains where thesearguments don't hold. I also encounter them from time to time. Anexample is outputting largeish matrices. These kind of judgements oftendepend heavily on what kind of coding you do. Which should be covered by the statement made earlier by James that one of the exception is outputing within a tight loop (e.g. each of the matrice lines) and then flushing immediately once one exits the loop. Surely all James is recommending is not to do premature optimisation. std::endl will always work and should be the first port of call. "\n" is an optimisation and should be used when needed. That seems clear and sensible to me. The reverse suggestion to always use "\n" by default and only add a std::flush when needed is premature optimisation. std::endl only slows down application that it slows down. If it does, then by all mean use "\n", if it doesn't, don't worry about it. Yan Sep 19 '08 #23

 P: n/a In article , James Kanze On Sep 18, 3:48 am, tony_in_da...@yahoo.co.uk wrote: >On Sep 17, 11:32 pm, James Kanze - some logging is found to be important but it's at TRACE/DEBUG/ DUMP and it's easier to change the process's threshold down than find and modify all the relevant debug statements, so production ends up with verbose logging permanently enabled. That's interesting. My experience is that most professionalsystems don't log enough. My experience is that they far too often managed to do both at the same time. Write too much data in the logs and not enough useful data. Yannick Sep 19 '08 #24

### This discussion thread is closed

Replies have been disabled for this discussion.