I've done this before. do you want it to take a specific line or just have it return the first and only?
This is the first version of my function. i have another that can return the line only if it starts with a specific substring
string getfile(string file, int line)
{
int j = 1;
string retdata;
string notfound = "line not found";
ifstream data( file.c_str() , ios::in);
while ( ! data.eof())
{
getline(data,retdata);
if (j == line )
{
data.close();
return retdata;
}
j++;
}
data.close();
return notfound;
}
or are you looking for a bool that just returns true if it is there?
lexusdominus
Junior Poster in Training
84 posts since Jun 2009
Reputation Points: 12
Solved Threads: 5
Where is "file" coming from in your listing in the OP?
jonsca
Quantitative Phrenologist
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
pass it a pointer if you want to change values across the function call. can you write out the function as you will be using it? i.e
int x = randomint(int highest, int lowest)
if you want to return every line you can just that function i posted and nest it inside a for loop. increment the variable "line" each loop and if the function returns "not found" have it break.
lexusdominus
Junior Poster in Training
84 posts since Jun 2009
Reputation Points: 12
Solved Threads: 5
Rather than have a global ifstream object, declare it in main() and pass it around by reference.
In your ReadLine function, what happens if your line doesn't contain any of those characters? If the function is not void, it's good practice to have a return for all possible paths through the function.
None of these problems should lead to a crash, though. It is more than likely something else. How did you determine that the function you posted was crashing the program?
jonsca
Quantitative Phrenologist
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
...Here is the code causing the app crash:
string ReadLine()
{
getline(file, lineread);
if (lineread.find_first_of("WSF_") != string::npos)
{
return lineread;
}
}
The function is basically badly broken -- what will it 'return' if lineread.find_first_of("WSF_") == string::npos ?
Aren't you getting any compiler warnings?
mitrmkar
Posting Virtuoso
1,809 posts since Nov 2007
Reputation Points: 1,105
Solved Threads: 395
ok, i think i understand you, you want it to just return the first line? the function getfile i showed you will do that. have a look through the code and see what it does. if you use it like so:
string data = getfile("Maze.txt", 1);
data will be equal to "WWWWWWWW". if you want the function to be used only for Maze.txt, just edit it accordingly.
lexusdominus
Junior Poster in Training
84 posts since Jun 2009
Reputation Points: 12
Solved Threads: 5