'C++ std::fstream how to move to a certain line and column of a file
So I have been searching on how to move to a certain line and column in a file , but I can't seem to find an answer . I want something like this :
std::fstream file("example.txt");
file.move_to( line number , column number );
Solution 1:[1]
The following function can do just you want:
std::string GetLine(std::istream& fs, long long index)
{
std::string line;
for (size_t i = 0; i <= index; i++)
{
std::getline(fs, line);
}
return line;
}
The above function gets the line at index (index == 0 - 1st line, index == 2 - 3rd line, etc.).
Usage:
#include <iostream>
#include <string>
#include <fstream>
std::string GetLine(std::istream& fs, long long index)
{
std::string line;
for (size_t i = 0; i <= index; i++)
{
std::getline(fs, line);
}
return line;
}
int main()
{
std::ifstream fs("input.txt"); // fstream works too
std::cout << GetLine(fs, 1);
}
input.txt
This is
a
test file
Output:
a
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Solved Games |
