School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!
Welcome to Dream.In.Code
Become an Expert!

Join 340,104 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 4,744 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* Rate Topic: -----

#1 moa-uk  Icon User is offline

  • New D.I.C Head
  • Pip
  • Group: New Members
  • Posts: 9
  • Joined: 10-May 09


Dream Kudos: 0

Post icon  Posted 10 May 2009 - 06:53 PM

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:
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:
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 :)
Was This Post Helpful? 0
  • +
  • -


#2 KYA  Icon User is online

  • while(sad){!sad; awesome();}
  • Icon
  • View blog
  • Group: Mentors
  • Posts: 13,183
  • Joined: 14-September 07


Dream Kudos: 3000

Expert In: C, C++, Java

Posted 10 May 2009 - 07:01 PM

If you can use std::strings why do you have to return a char*?
Was This Post Helpful? 0
  • +
  • -

#3 moa-uk  Icon User is offline

  • New D.I.C Head
  • Pip
  • Group: New Members
  • Posts: 9
  • Joined: 10-May 09


Dream Kudos: 0

Posted 10 May 2009 - 07:02 PM

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
Was This Post Helpful? 0
  • +
  • -



Fast Reply

  

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users



Live Help!

Be Social

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

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month