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 );
CodePudding user response:
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