I need a function that reads from a txt file and randomly chooses a line
from which retrieves a string (with spaces) and returns it to main function.
thx 14 1461
Nikola writes: I need a function that reads from a txt file and randomly chooses a line from which retrieves a string (with spaces) and returns it to main
function.
I assume this is a student problem. Try breaking the problem down. You can
not choose a random line until you know how many lines there are. So you
must start by counting the lines. To count the lines you will have to read
the lines. To read the lines you will have to open the file. To open the
file you must know the file name. And so on. Writing things down in some
form can be a great help. The preferred method is called pseudocode but any
form at all is better than just fussing and flailing.
in comp.lang.c i read: I need a function that reads from a txt file and randomly chooses a line from which retrieves a string (with spaces) and returns it to main function.
i bet you do. when is your homework due?
--
a signature
osmium wrote: Nikola writes:
I need a function that reads from a txt file and randomly chooses a line from which retrieves a string (with spaces) and returns it to main
function.
I assume this is a student problem. Try breaking the problem down. You can not choose a random line until you know how many lines there are.
There are perfectly good ways to choose a line at random
without knowing in advance how many there are. In fact, you can
choose a random sample of N lines without advance knowledge; the
case N==1 is particularly easy, but N>1 isn't difficult. See
Knuth "The Art of Computer Programming, Volume II: Seminumerical
Algorithms," section 3.4.2, Algorithm R.
(Well, I guess you do in fact need *some* advance knowledge.
Specifically, you need to know that the source of random numbers
can deliver a different value for every line in the file, without
repetitions. A PRNG that will deliver two billion distinct
"good" numbers is easy to write in portable C; four billion is
also easy at some small sacrifice of "goodness." So the advance
knowledge amounts to knowing that the file holds fewer than four
billion lines; I think this may be considered axiomatic in the
context of a simple homework assignment.)
-- Er*********@sun .com
No, it's not a home work and yes, I am a begginer (weren't we all??) and
trying to do a little code of my own - was told that ambition is a virtue
:-)
On Fri, 14 May 2004, Eric Sosman wrote: osmium wrote: Nikola writes:
I need a function that reads from a txt file and randomly chooses a line from which retrieves a string (with spaces) and returns it to main function.
<snip> You cannot choose a random line until you know how many lines there are. There are perfectly good ways to choose a line at random without knowing in advance how many there are.
<snip> (Well, I guess you do in fact need *some* advance knowledge. Specifically, you need to know that the source of random numbers can deliver a different value for every line in the file, without repetitions.
...Or, I think more generally, you can be satisfied with a RNG
that will return an unbiased random number in the range 1..n, for
every n in the range 1..N where N is the number of lines in the
file. That may be what you were getting at; after all, if the
RNG can deliver a number in the range 1..N, then in some sense it
must be able to deliver N different numbers "without repetition."
Of course, it doesn't need to generate its random numbers without
repeating itself --- that would be a pretty bad RNG! ;)
Okay, enough hints from me now. :)
-Arthur
Nikola wrote: No, it's not a home work and yes, I am a begginer (weren't we all??) and trying to do a little code of my own - was told that ambition is a virtue :-)
Then you need to show us this "little code". Just giving us the problem
spec and requesting an answer doesn't really display much in the way of
ambition.
What have you figured out so far? What is your analysis of the problem?
Do you know how to open a file? Read out a line? How would you choose a
random line?
Brian Rodenborn
> What have you figured out so far? What is your analysis of the problem? Do you know how to open a file? Read out a line? How would you choose a random line?
Well, nothing anyone said didn't help so I kept trying ...
If there are some noncence-mistakes in my code that no self-respectfull
programmer would make
keep in mind that I'm just 19, meaning, a begginer
this code should read the random line of an file
commented parts were just a unsuccessfull toughts....
it's not in english this is the translation of some words:
znak-character
br_redaka-number of lines
brojac-counter
pojam-randomly chosen line (string)
this is ment to be a function that returns a string ...
FILE *dat;
char pojam[50],c,znak;
int br_redaka=1,bro jac=1,rand_br;
dat=fopen("film .txt","r");
while(c!=char(E OF))
{
c=getc(dat);
if(c==char(10)) //10 - ascii for new line
br_redaka=br_re daka+1;
}
//generiranje nasumicnog broja od 0 do broja redaka //moguci BUG zbog
nule!
srand(time(NULL ));
rand_br=rand() % br_redaka;
c='b';
while(c!=EOF)
{
/*c=getc(dat);
if(c==char(10)& &brojac==rand_b r) //10-ascii kod za novi redak
{
brojac=brojac+1 ; //rand_br od 0 do br_redaka
fgets(pojam,50, dat);
}*/
c=getc(dat);
if(c==char(10)& &brojac==rand_b r)
{
brojac=brojac+1 ;
while(znak!='\\ ')
//strcat(pojam,zn ak);
pojam[brojac-2]=c;
}
}
printf("%s",poj am);
Arthur J. O'Dwyer wrote: On Fri, 14 May 2004, Eric Sosman wrote:
osmium wrote:
Nikola writes:
I need a function that reads from a txt file and randomly chooses a line (Well, I guess you do in fact need *some* advance knowledge. Specificall y, you need to know that the source of random numbers can deliver a different value for every line in the file, without repetitions .
...Or, I think more generally, you can be satisfied with a RNG that will return an unbiased random number in the range 1..n, for every n in the range 1..N where N is the number of lines in the file. That may be what you were getting at; after all, if the RNG can deliver a number in the range 1..N, then in some sense it must be able to deliver N different numbers "without repetition."
The algorithm I'm thinking of actually needs N distinct
values. Simply knowing that the range of generated numbers
contains more than N values is not good enough, nor is knowing
that the period of the PRNG exceeds N. You actually need a
"no duplicates among the first N values" guarantee.
At the risk of becoming almost topical: rand() itself lacks
such a guarantee, but it would be possible to write a wrapper
around rand() to get this behavior.
Of course, it doesn't need to generate its random numbers without repeating itself --- that would be a pretty bad RNG! ;)
I don't understand what this means.
-- Er*********@sun .com
On Fri, 14 May 2004 19:38:17 +0200, "Nikola" <az*****@inet.h r> wrote: Well, nothing anyone said didn't help so I kept trying ... If there are some noncence-mistakes in my code that no self-respectfull programmer would make keep in mind that I'm just 19, meaning, a begginer this code should read the random line of an file commented parts were just a unsuccessfull toughts.... it's not in english this is the translation of some words:
znak-character br_redaka-number of lines brojac-counter pojam-randomly chosen line (string)
this is ment to be a function that returns a string ...
FILE *dat; char pojam[50],c,znak; int br_redaka=1,bro jac=1,rand_br; dat=fopen("film .txt","r"); while(c!=char(E OF))
I see three problems.
Firstly char(EOF) is a syntax error.
Secondly getc() returns an int, not char.
Thirdly object c is used before it has been initialised.
Also testing for EOF before calling getc() is bad style. It
results in the loop executing one too many times, although
in your case the result of this is harmless. It is better
to write this loop as:
while (c=getc(dat), c!=EOF)
{
/* ... */
}
This also ensures that object c is initialised before the
comparision.
{ c=getc(dat); if(c==char(10)) //10 - ascii for new line
This is also bad style. It needlessly restricts your program to
only working on ASCII implementations . Since the file is open
in text mode you can write:
if (c=='\n')
br_redaka=br_re daka+1; } //generiranje nasumicnog broja od 0 do broja redaka //moguci BUG zbog nule! srand(time(NULL )); rand_br=rand() % br_redaka;
See Q13.16 in the FAQ: http://www.eskimo.com/~scs/C-faq/q13.16.html
You also need to reset the file pointer here:
fseek( dat, 0, SEEK_SET );
c='b'; while(c!=EOF) { /*c=getc(dat); if(c==char(10)& &brojac==rand_b r) //10-ascii kod za novi redak { brojac=brojac+1 ; //rand_br od 0 do br_redaka fgets(pojam,50, dat); }*/ c=getc(dat); if(c==char(10)& &brojac==rand_b r) { brojac=brojac+1 ; while(znak!='\\ ') //strcat(pojam,zn ak); pojam[brojac-2]=c;
This while loop would appear to be infinite. I don't think it's
even needed.
} }
You need to null terminate the char array to turn it into a valid
string for display:
projam[brojac-1] = '\0';
printf("%s",poj am);
Nick. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Sofia |
last post by:
My name is Sofia and I have for many years been running a personals site,
together with my partner, on a non-profit basis. The site is currently not
running due to us emigrating, but during its last year we got traffic of
between 2000 - 2500 unique visitors per day. We are now about to re-launch
the site from Sweden and we need to purchase a script to run it.
Having looked at what is available on the net I have realised that we need a...
|
by: Robert Maas, see http://tinyurl.com/uh3t |
last post by:
System login message says PHP is available, so I tried this:
http://www.rawbw.com/~rem/HelloPlus/h.php
It doesn't work at all. Browser just shows the source.
What am I doing wrong?
|
by: Gregory Nans |
last post by:
hello,
i need some help to 'tree-ify' a string...
for example i have strings such as :
s = """A(here 's , B(A ) silly test) C(to show D(what kind) of stuff i
need))"""
and i need to parse them to have a tree representation such as :
|
by: Mike Kamermans |
last post by:
I hope someone can help me, because what I'm going through at the moment
trying to edit XML documents is enough to make me want to never edit XML
again.
I'm looking for an XML editor that has a few features that you'd expect
in any editor, except nearly none of them seem to have:
1 - Search and repalce with Regular Expressions.
2 - Search and Replace in an Xpath context.
3 - User specified tag-generation for either on a...
|
by: JustSomeGuy |
last post by:
I need to write an new class derived from the list class.
This class stores data in the list to the disk if an object
that is added to the list is over 1K in size.
What methods of the std stl list class must Ioverride in order for this
to work?
| |
by: Bob.Henkel |
last post by:
I write this to tell you why we won't use postgresql even though we wish we
could at a large company. Don't get me wrong I love postgresql in many
ways and for many reasons , but fact is fact. If you need more detail I
can be glad to prove all my points. Our goal is to make logical systems.
We don't want php,perl, or c++ making all the procedure calls and having
the host language to be checking for errors and handleing all the...
|
by: Michael R. Pierotti |
last post by:
Dim reg As New Regex("^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$")
Dim m As Match = reg.Match(txtIPAddress.Text)
If m.Success Then
'No need to do anything here
Else
MessageBox.Show("You need to enter a valid IP Address", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Hand)
txtIPAddress.Focus()
Return
End If
|
by: skumar434 |
last post by:
i need to store the data from a data base in to structure
.............the problem is like this ....suppose there is a data base
which stores the sequence no and item type etc ...but i need only the
sequence nos and it should be such that i can access it through the
structure .plz help me .
|
by: Alan Mailer |
last post by:
A project I'm working on is going to use VB6 as a front end. The back
end is going to be pre-existing MS Access 2002 database tables which
already have records in them *but do not have any AutoNumber* fields
in them.
Correct me if I'm wrong, but I'm assuming this means that I cannot now
alter these existing Access tables and change their primary key to an
"AutoNumber" type.
If I'm right about this, I need some suggestions as to the...
|
by: U S Contractors Offering Service A Non-profit |
last post by:
Brilliant technology helping those most in need Inbox
Reply
U S Contractors Offering Service A Non-profit
show details
10:37 pm (1 hour ago)
Brilliant technology helping those most in need Inbox
Reply
from Craig Somerford <uscos@2barter.net>
hide details 10:25 pm
(3 minutes ago)
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |