Hello, so I'm fairly new to C++ but not to programming overall. I have created a simple TXT file with about 15 words in them, and I would like to write a program which asks me for a number of words, you type it in (simple cout, cin) and it gets the number of words you selected randomly from my text files and outputs them.

So the program would be like:

How many words would you like?
user: 6
program: selects 6 random words from TXT file and prints them on screen.

I hope this makes sense, and I would be happy to provide more information if needed

Files work best for saving data, not using data interactively, as the response time for retrieving data from file is slow compared with finding data from within RAM. For doing what you want with 15 words it is much easier to read all the words into a container, and an array or a vector would be reasonable choices given your desire to randomly access the values in the container. Once the words have been read into the container then create a protocol to randomly (as you can) select words from it. That is most often done using srand() to prime the random number generator called rand() and using the appropriate manipulations to the value returned by rand() to get it into the range you want (probably zero to one less than the number of elements in the container). File reading and random number generation are common protocols discussed on the board and in many references. Give it a shot and come back when you have a specific question.

Edited 6 Years Ago by Lerner: n/a

That's what I am trying to do but am not exactly sure how to get my file contents into an array.

That's what I am trying to do but am not exactly sure how to get my file contents into an array.

Well there are a bajillion ways to do that but.... a quick dirty way:

fstream iFile("myFile.txt", ios::in | ios::beg);
const int MAX = 15;
string words[MAX];
int index = 0;

while (cin >> words[index] && index++ < 15);

Edited 6 Years Ago by hag++: n/a

This article has been dead for over six months. Start a new discussion instead.