I was wondering if someone could help me write the code for this...

I have a text file with 10 lines, one word on each line and I am trying to get a word from a random line and then cout that word. Can anyone help?

Recommended Answers

All 9 Replies

What part of this is giving you a problem?

What part of this is giving you a problem?

I know how to write the code to get the word on the first line of the text file, but my program has to get a random word, so I'm just not really sure how to go to random line and get the word from that line only.

Why don't you read the contents into a vector then generate a random number less than 10 and print the string at that location in the vector?

// DW_392202.cpp
#include <time.h>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
//
int main(void)
{
	ifstream fileIn("c:/science/DaniWeb/DW_392202/input.txt");
	char strData[128] = {0};
	vector<string> lst;
	int intNumLinesRead = 0;

	while(!fileIn.eof())
	{
		fileIn >> strData;
		if(0 != strData[0])
		{
			lst.push_back(strData);
			intNumLinesRead++;
		}
	}
	fileIn.close();

	srand(time(NULL));
	int intOffset = (rand() % intNumLinesRead);
	vector<string>::iterator it = lst.begin()+intOffset;

	cout << (*it).c_str();
	return 0;
}
commented: Why are you doing homework for people? -4

If he's having trouble reading a file and looking at the words, and won't post code
1) what makes you think he's been taught vectors?
2) why are you the one posting code?
3) why are you doing his homework for him?
4) why are you using a bad form for your loop counter that is a logic error?

All in all, two very bad posts.

...maybe I should have used Microsoft Foundation Classes.

I have a text file with 10 lines, one word on each line and I am trying to get a word from a random line and then cout that word.

Take note that since there's only one word on each line, the problem can be restated as trying to get a random line. That's a smidge simpler than a random word where each line can have multiple words.

In fact, you can do it without storing all of the lines as in thines01's example. For ten lines using a vector isn't a big deal, but if you want to find a random line in a huge file (on the order of gigabytes) then it's wiser not to read the whole thing into memory. Here's an (intentionally advanced) example:

#include <algorithm>
#include <climits>
#include <cmath>
#include <cstddef>
#include <ctime>
#include <functional>
#include <fstream>
#include <iostream>
#include <map>
#include <random>
#include <string>
#include <utility>

unsigned time_seed()
{
    std::time_t now = std::time(nullptr);
    unsigned char *p = (unsigned char*)&now;
    unsigned seed = 0;

    for (std::size_t i = 0; i < sizeof now; i++)
        seed = seed * (UCHAR_MAX + 2U) + p[i];

    return seed;
}

class random_line
{
public:
    random_line(): generator(time_seed()) {}

    std::pair<long long, std::string> operator()(const char *filename) {
        std::ifstream in(filename);
        std::string line;

        if (in && std::getline(in, line)) {
            std::string picked_line = line;
            long long picked_index = 0;
            long long i = 0;

            // Reservoir sampling method so we don't have to store all lines
            do {
                auto random = std::uniform_int_distribution<>(1, ++i);

                if (random(generator) == 1) {
                    picked_line = line;
                    picked_index = i;
                }
            }
            while (std::getline(in, line));

            return std::make_pair(picked_index, picked_line);
        }

        return std::make_pair(-1, "");
    }
private:
    std::mt19937 generator;
};

int main()
{
    const long long nruns = 10000;
    
    std::map<long long, unsigned> dist;
    random_line rline;

    // Get a random line N times for a distribution test
    for (long long i = 0; i < nruns; i++)
        ++dist[rline("test.txt").first];

    typedef std::pair<long long, unsigned> pair_t;

    auto square = [](long long x) { return x * x; };
    long long mean = std::accumulate(dist.begin(), dist.end(), 0,
        [](long long x, pair_t const& y) { return x + y.second; }) / dist.size();
    long long variance = std::accumulate(dist.begin(), dist.end(), 0,
        [=](long long x, pair_t const& y) { return x + square(y.second - mean); }) / dist.size();
    long long deviation = std::sqrt(variance);
    
    // Distribution results for smaller files (arbitrary size...)
    if (dist.size() <= 100) {
        for (auto x : dist)
            std::cout << x.first << ": " << x.second << '\n';
    }

    // Distribution metrics for all files
    std::cout << "Mean:               " << mean << '\n'
              << "Standard Deviation: " << deviation << '\n';
}

If he's having trouble reading a file and looking at the words, and won't post code
1) what makes you think he's been taught vectors?
2) why are you the one posting code?
3) why are you doing his homework for him?
4) why are you using a bad form for your loop counter that is a logic error?

All in all, two very bad posts.

ouch...

but anyways i just ended up putting fin.ignore in a for loop that ran a random number of times less than ten and then I would cout that line.
Thanks for the help

Great example, Narue!
This will serve well as a resource every time the question comes up :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.