i am trying to get text file and read only first 100 lines of the text content using c/c++. how can i do it?
is it something like string line;
getline(stream,line);
??
i am trying to get text file and read only first 100 lines of the text content using c/c++. how can i do it?
is it something like string line;
getline(stream,line);
??
You are on the right track, but you may also want a loop.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Considering you want to read the first 100 lines, you need to store each line in a variable. A vector would be the best solution.
So start by defining a vector and a string (line) so you can store each line in each vector's position.
If you wanted just a couple of lines, you'd be better off repeating the code you posted previously plus pushing the string into the vector, but considering you're willing to do it 100 times, just create a loop from 0 to 99/100, get each line of the file (getline) and push it back to the vector (myVector.push_back).
Learn some more about them, they are essential.
vector - C++ Reference
To store the first line in a vector:
Code:string line; vector<string> MyVector; ifstream MyFile("example.txt"); getline(MyFile, line); //Gets the first line of the file MyVector.push_back(line); //Pushes it to the vector
If you provide us with some code then we can help guide you towards your goal.
I would recommend breaking down your problem into steps.
1. Do something 'x' ammounts of times
2. For each x, read at the location
- the location should be a line
Based on the above steps, it would look as if you would need something to loop for step 1, and within the loop, you would need to
do a read call, which involves reading a sentence. I would search around the site at I/O and it will help you with understanding how to read a line of text from a text file.
Please post your solution once you are done in here so that others may benefit from it.
some code which i tried with, but actually here it prints on the standard i/o which i dont want to...
Code:#include <iostream> #include <fstream> #include <string> using namespace std; int main () { string str; ifstream ifs("test.txt"); getline (ifs,str); cout << "the first line of the file is " << str << ".\n"; }
Standard I/O is just I/O like any other file. If you can work with stadnard i/o (ie cout, cin), then you can work with files too.
Just use the correct stream for reading and writing. It will be exactly the same otherwise (except standard streams are always open; files you have to open manually).