Reading Lines from Text File

Oct 21, 2008 at 12:26am
I have searched many a site to find an answer to this question, so here goes:
(This is actually C, not C++ so bear with me)

I'm doing a hangman program that needs to pull different quotes from a text file named quotes.txt. Each quote is on a different line. I have the entire hangman program written (I can post later, if need be), but I need to write a function to get the quote, calculate the quote length, AND convert the entire quote to uppercase(I thnk I'm fine with that part though)

My variables are as follows:
(X is the length of the quote which will need to be calculated)
char realquote[x] contains the quote as it is written in the text file.
char quote[x] contains the quote written in all capitals

The function begins as follows:
1
2
3
4
void GetQuote()
{
   //This is where I need code to pull the quote
}


I will have approximately 10 quotes stored in the text file (One per line, as mentioned before). I would like to generate a random number between 1 and 10 and pull the quote from that line into the realquote array. I then need to determine the actual string length (I'm assuming I will use strlen or something like that?).

Any and all help with this would be greatly appreciated. Like I said, I can post up the entire Hangman program so you can see how it fits in, but I believe I've provided all relevant information to this specific part!

Thanks!
Madd0g
Oct 21, 2008 at 12:29am
Do you want the answer in C or C++?
Oct 21, 2008 at 12:30am
It has to be C (I know this is a C++ forum, but unlike many others, this forum seems to actually be active!)

BTW, I am currently using
#include <stdio.h>
#include <string.h>
#include <ctype.h>
Last edited on Oct 21, 2008 at 12:31am
Oct 21, 2008 at 12:31am
Oct 21, 2008 at 12:40am
I've read up on fgets, fread, fopen, etc. but I guess I'm a little hairy on exactly the way to call it. Could you possibly write a sample with comments so I know what each part is actually doing.

For example:
fread(buffer,realquote[x],1,"quotes.txt")
Buffer = tempory place to store
realquote[x] = array to store it in
1 = line to read
quotes.txt = file to pull from
(I know that's not what fread actually is/does, I just made up that sample)
Oct 21, 2008 at 12:51am
http://www.cplusplus.com/reference/clibrary/cstdio/fgets.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* fgets exmaple */
#include <stdio.h>

int main()
{
   FILE * pFile;
   char mystring [100];

   pFile = fopen ("myfile.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else {
     fgets (mystring , 100 , pFile);
     puts (mystring);
     fclose (pFile);
   }
   return 0;
}
Oct 21, 2008 at 1:16am
I saw that example before, but my question with that is, where do i specify what line I want to pull?
Topic archived. No new replies allowed.