C
C
csar2016-05-02 23:38:14
C++ / C#
csar, 2016-05-02 23:38:14

How to read file line by number?

Faced such a problem:
1. I open a file
std::ifstream file("test.cfg");
2. I count the number of lines

while (std::getline(file,line)) {
        ++count;                                    
    }

3. I call srand, then
num=rand()%count
4. How do I read the line number num?
PS
By the way,
file.seekg (0, file.beg);
does not help. After it, file>>line outputs a void.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AtomKrieg, 2016-05-03
@csar

#include <fstream>
#include <string>
#include <vector>
#include <iostream>

int main()
{
  std::ifstream file("test.cfg");
  std::vector<std::string> buffer;
  std::string line;
  while (std::getline(file,line)) {
    buffer.push_back(line);
  }
  std::cout << buffer[rand()%buffer.size()] << std::endl;

  system("pause");
  return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question