Hello, I'm writing a program for my brother. I'm a beginner in these things. So, what I want from a program is that it'll write random word and then ask continue? press y/n... if n/N, the program will exit, if y/Y, the program will start over by writing random word again. I already did the random word chooser, but I can't go back to the start of a program. How can I do this? Thanks for any respone and sorry for my english, it's not my first language.
I would advice using a do-while loop. This loop is always executed at least once. You would end up with something close to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int main()
{
bool cont;
srand(time(0));
do
{
//Other code
...
//The letter the user entered
char letter;
//Ask for a letter and read one
cout << "Do you want another word? [Y/N] ";
cin >> letter;
//Set our continue flag, this will be true if the letter entered is Y or y
cont = letter == 'Y' || letter == 'y';
}while(cont);
return 0;
}
The do-while loop is executed at least once, and goes on as long as the variable cont is set to true. It will be set to true whenever the letter the user entered is either Y or y, and it will be set to false otherwise, breaking the loop and thus stopping the program.
Thanks you very much! It is working, but I've got another problem. The words that I put in can repeat for example first word is icecream, then i press y, then enter and it can be icecream again, can I do it like if (word = icecream) {//next command will delete icecream from the other words
Im really beginner at programing, and very young to programme more difficult programms tho.
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main(int argc, char* argv[]) {
bool cont;
srand(time(0));
do
{
const string wordList[4] = { "icecream",
"computer", "dictionary", "algorithm" };
string word = wordList[rand() % 4];
cout << word << endl;
char letter;
cout << "Do you want another word? [Y/N] ";
cin >> letter;
//Set our continue flag, this will be true if the letter entered is Y or y
cont = letter == 'Y' || letter == 'y';
system("cls");
}while(cont);
return 0;
}
You could use a vector to store your constants, and remove the elements as required. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
vector<string> values = {"icecream", "computer", "dictionary", "algorithm"}; //Initialize the vector
//Some other code
...
//The do-while loop
do
{
//Fetch a new word
string word = values[rand() % values.size()];
//Print it
cout << word << endl;
//Removing the element
vector<string>::iterator position = std::find(values.begin(),values.end(),word); //Find the position of our word
values.erase(position); //And delete the element
//Ask if we should go on
...
}while(cont && values.size() != 0); //Go on as long as there are still values left