I've written the Cookie Monster program to test my memory on what I've learnt so far. However, when I run the program, if the user enters several words, the message in the while loop repeats itself for the amount of words are in the string. I can't figure out why. Any ideas? :)
Using >> on cin reads as far as the next white space or the end of input. This leaves anything after that white space still to be read. Next time, it will again read to the next white space, and so on.
Your program seems to work fine to me....i dont see any problem, but if you have some kind of problem you can try cin.ignore() before cin statement in loop, that might help your code!
Thank you, ui uiho and firedraco, I wasn't aware. What should I use instead? DOS opens and closes so rapidly and I can't install Linux (my OS of choice) on my machine in the forseeable future.
there are a few ways to do this, one you could make your own wait function to keep the consul open for a second after completion of the program. here is the wait function i use.
1 2 3 4 5 6
int wait ( int seconds ){// include time.h library
clock_t endwait;
endwait = clock() + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
return 0;
}
this does the same thing as system("PAUSE"); but it does not call to the OS for the function, you write it yourself in the code, which is safer and faster. another thing that you can do is write your own exit function.
1 2 3 4 5
int exitfunc(){
std::cout << "Press ENTER to exit...";
std::cin.ignore(/*put in limits if you want*/);
return 0;
}
this will allow you to control the time the program closes.
otherwise std::cin.ignore() will work at the end of your program as long as your cin buffer is empty. i would prefer the wait function because you do not have to worry about the cin buffer and you can use it throughout your program if you ever want to do something like a countdown, but the option is up to you and the one you select should vary depending on the program you are running.
Without adding any extra code the best way to keep your program open is by (instead of just double clicking the .exe) going into command prompt and executing it from there (just type the program's name, for example type "myprog.exe") and you'll be able to see the output.