In C++ how would I go about getting a specific lin

2019-06-05 16:37发布

I want to have my program open a text file, go down to a specific line (for example, line 18) and store each character on that line in a char vector.

I'm fairly new to programming in general so this may not be the best way but here's what I plan on doing:

1) Get specific line and store it in a string

2) Convert that string to a char vector. I'm using a vector instead of an array so I can use pushback() to make the vector the exact size needed instead of allocating too much or too little in an array.

I can do step 2 just fine but it is step 1 I'm having trouble with. How do I make it go to a specific line?

1条回答
欢心
2楼-- · 2019-06-05 17:12

Just read all lines and ignore those you are not interested in:

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

int main()
{
        std::ifstream file("file.ext");
        std::string line;
        unsigned int line_number(1);
        const unsigned int requested_line_number(4);
        while (std::getline(file, line))
        {
                if (line_number == requested_line_number)
                {
                        std::cout << line << "\n";
                }
                line_number++;
        }
}

This code is of course devoid of error handling, and naturally, you wouldn't want to hardcode your line number most of the time, but you get the idea.

Also, I don't really see what the char vector / array is for. Use std::string for your string handling needs, that's what it's made for.

查看更多
登录 后发表回答