I'm having trouble understanding the model from the tutorial...Here is my code, basic file in/out...How do I read a specific line from a text file?
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <fstream>
#include <sstream>
int main() {
string line;
ifstream myfile ("c:\output.txt");
getline( myfile, line ); //Can I direct the compiler to read a certain line (ie. line 180)?
myfile.close();
return 0;
}
thank duoas...but is there no way to scroll to a certain line?
I'm taking a txt file from the internet that contains statistics for 32 teams (NFL)...the file is constant...the only differences are the numbers within the lines I need to read. So, my thought was to scroll to certain lines and use delimiters to extract the information. It sounds though like my method will be more complicated than just scrolling to line 180...is that correct?
Like Duoas said, you can only skip directly to a line when you can make some assumptions about the file, like "all lines have 80 characters".
"Files are just\narrays of bytes without inherent\nstructure. If a line can be of any length,\nyou can only count newline\ncharacters to know which line you're on.\n"
if I know the size of each line, how would I skip to line 180 if all lines have 80 characters?
can you search a file for certain characters, strings, etc..?
also, the file is from a webpage(html)...most of the lines are like the following, which throw errors while declaring the line as a string:
EDIT: also, I doubt every line has exactly 80 characters, so that's probably not a good way to approach the problem.
I would just scan the file for newline characters ("\n"). Once you found the 180th newline character you're on the 180th line. So just keep reading characters from the file and ignore them until you get to the 180th newline.
ok thanks all...i know not every line has 80 characters...just theory i'm interested in...i'm trying to find ways to search through the text file...I will go line by line searching for delimiting characters to extract the info...
EDIT: just read your edit disch...that method makes sense...I will try it, thanks!
I used a similar method to that of Disch's...added a count to the while() statement so that when count = 180, print the line. works ok...
1 2 3 4 5 6 7 8 9 10 11 12
string line;
int count=0;
ifstream myfile ("c:/output.txt");
while(myfile.good()) {
getline(myfile, line);
count++;
if(count==180) {
cout << line << endl;
... //here I can use info from "line"
}
}