Answer the question
In order to leave comments, you need to log in
How to make random output from c++ file?
In general, there is such a task, I write the n-th number of words to a file, by a word in a line
Example:
Man
Beetle
Guinea
I need it to display a random word from the list when starting the program. Help me please.
I tried the method getline()
, and did not understand how this function saves. With the help of a vector, I didn’t think of it either. I made a conclusion, it's elementary, but I didn't figure out how to organize it randomly.
Answer the question
In order to leave comments, you need to log in
#include <iostream>
#include <string>
#include <fstream>
#include <time.h>
using namespace std;
int main() {
srand((unsigned int)time(0));
int n = 10; // количество строк в файле
int random = rand() % n + 1;
ifstream in("test.txt");
string result;
for (int i = 0; i < random; i++) {
getline(in, result);
}
cout << result << endl;
system("pause");
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question