|
|
|
|
|
|
This will skip everything up to and including the next newline character (\n). file.ignore(1000, '\n'); The first argument is the maximum number of characters that will be skipped. Above I used 1000 but if you want to handle longer lines than that you can just pass in a larger value. The maximum number that you can pass in is std::numeric_limits<std::streamsize>::max() so this is what you often see people use. file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); By calling this in a loop you can skip to the line that you want. |
inputFile.seekg(0, ios::beg);
to reset the read position to the beginning of the file, you could use a loop that runs the code I just showed n-1 times in order to jump to the n:th line. And then afterwards, you just read the content of that line the way that you want.
|
|
So, right after you have opened the stream, or after using something like inputFile.seekg(0, ios::beg); to reset the read position to the beginning of the file, you could use a loop that runs the code I just showed n-1 times in order to jump to the n:th line. And then afterwards, you just read the content of that line the way that you want. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #include <iostream> #include <fstream> #include <limits> void jumpToLine(std::istream& os, int n) { // Clear error flags, just in case. os.clear(); // Start reading from the beginning of the file. os.seekg(0, std::ios::beg); // Skip to line n. for (int i = 1; i < n; ++i) { os.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } int main() { std::cout << "Which file do you want to read from? "; std::string filename; std::cin >> filename; std::cout << "Which line number do you want to print? "; int lineNumber; std::cin >> lineNumber; std::ifstream file(filename); jumpToLine(file, lineNumber); std::string lineContent; std::getline(file, lineContent); std::cout << "The content of line " << lineNumber << " is \"" << lineContent << "\"\n"; } Edit & Run |
nearc wrote: |
---|
I'm getting errors no matching function call to max() and primary expression before > |
llll wrote: |
---|
is it possible for you to explain what does this line mean or doing os.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); |