In need of professional help!

So I'm making a hangman game and the problem I'm having involves me using a random number generator
in order to pick a line from a text file. As such I get a random number but, I don't know how to
cout a specific line of the text file using the random number I got.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
using namespace std;

int main()
{
	
	unsigned seed = time(0); //Gets the system time
	int y = 1; // sets y as a int value type
	srand(seed); // Seed the random number generator
	
	string word;
	int random;
	
	fstream inputFile;
	inputFile.open("genwords.txt", ios::in);
	/*const int HM_SIZE = 100;
	string word[HM_SIZE];
	int choose = y;
	*/
	
	const int MIN_VALUE = 1; 
	const int MAX_VALUE = 100;
	y = (rand() % (MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE; // Limits the range of random   numbers to be
														   // 1 -100
	cout << y << endl; //couts the random number

	cout << "Please re-enter your number\n";
	
	cin >> random; // asks the user to enter their number


	getline(cin, word); // gets a line from the file

	inputFile << word << endl;

	cout << word << endl;
	
	inputFile.close();
		
	system("pause");
	return 0;
}
Last edited on
You could use a loop that calls getline until you get to the line that you want to read.
So implement a for loop to keep calling the getline?
A for loop or perhaps a while loop. Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int num = 9;  // this is the line we want
        
    ifstream fin("data.txt");
    string line;
    int count=0;
    
    while (getline(fin, line) && ++count < num)
        ;  // empty loop body 

    if (fin)
        cout << "line number " << num << ":\n" << line << endl;
    else
        cout << "file read error" << endl;
    
    return 0;
}
Thank you so much ^ it worked when I took line 8 and changed int num = 9 to int num = y
Topic archived. No new replies allowed.