Answer to Question #2527 in C++ for kim

Question #2527
How do you read text from file then use the random number generator to randomly select words?
I know you use fstream but I don't know what else to put.
Thanks
1
Expert's answer
2011-06-24T07:19:51-0400
One of the ways to doing your task is as follows.

By "word" we will mean a sequence
& a1, ... an
of chars such that
& 1) every& ai& is a letter, that is one of the symbols& A-Za-z
& 2) a1 is either the first symbol in the file,
or the symbol in the file previous to a1 is not a letter
& 3) an is either the last symbol in the file, or the next symbol is not
a letter.

To "encode" the word in the file it suffices to remember two numbers:
* the position of a1 in the file
* the length& n& of the word

=======================

0) include the following libraries

#include<string>
#include<vector>
#include<stdlib>
#include <iostream>
#include <fstream>
using namespace std;


1) Write function

& int isLetter(char c);

returning 1 if c is one of symbols A-Za-z
and 0 otherwise


2) Create a structure
struct word
{
& int pos;
& unsigned int length;
};

// further create a vector whose elements will be instances of word
structure.
vector<word> word_list;

3) Read consequtively bytes from file and recognize words.
If the word w is found, so it is defined with two numbers
pos and length
add it to the vector via the command

& word_list.push_back(w);

during extraction you can also calculate the maximal length
& int max_length;
among all words.
This number will be used below for printing words.


4) Now you can use function
& i = rand(word_list.size())
to get a random index

5)& To print word with index i via the following function

print_word(word w, istream file, ostream out)
{
// create a buffer unough to contain the word;
char buffer[1000];
// set position in the file to the beginning of the word
file.seekg(w.pos, ios::beg);
// read the word
is.read(buffer,w.length);
// put symbol 0 after the word, to create null-terminated string
buffer[w.length]=0;
out << buffer;
};

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS