C++ School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C++ Expert!

Join 300,337 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,659 people online right now. Registration is fast and FREE... Join Now!




Read random line from txt file and return it as char*

 

Read random line from txt file and return it as char*

moa-uk

10 May, 2009 - 06:53 PM
Post #1

New D.I.C Head
*

Joined: 10 May, 2009
Posts: 9


My Contributions
Hello everyone, I have a problem making a function which reads a line off a wordbank and then returns it as a char*

I managed to do this, but it returns it as a string:
CODE

string PickaLine(){
fstream file;
file.open("MyPhrases.txt");
string line2;

int y=0;
string selected_line; // added
char thelinetouse;

line2=y;
selected_line=y;

      int nlines = 0;
      while( getline( file, line ) )
         if(  ( rand() % ++nlines  ) == 0 ) // break;
                  selected_line = line;

    
    return thelinetouse;
}



Also I found this on the internet, it returns a char, but only one word, not a whole sentence:
CODE

char* PickaLine2(){
ifstream in ( "MyPhrases.txt" );
char word[22];

srand((unsigned)time(0));

if ( !in )
  return 0;

int r = rand() % linescount; // Assuming 10,000 words in the file

do
  in>> word;
while ( --r >= 0 );
cout<< word;
return word;

}



The txt files has one phrase per line, no more than 20 characters, including spaces which should also be included in the return value.

Please help smile.gif

User is offlineProfile CardPM
+Quote Post


KYA

RE: Read Random Line From Txt File And Return It As Char*

10 May, 2009 - 07:01 PM
Post #2

#include <nerd.h>
Group Icon

Joined: 14 Sep, 2007
Posts: 11,187



Thanked: 489 times
Dream Kudos: 2825
Expert In: C, C++, Java

My Contributions
If you can use std::strings why do you have to return a char*?
User is online!Profile CardPM
+Quote Post

moa-uk

RE: Read Random Line From Txt File And Return It As Char*

10 May, 2009 - 07:02 PM
Post #3

New D.I.C Head
*

Joined: 10 May, 2009
Posts: 9


My Contributions
Becasue I have to take this line to an array by:

strcopy(Array, Pickaline());

so I can work on it - im nearly finished with my program, thats the last thing I need
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic

Time is now: 11/7/09 05:09PM

Live C++ Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month