In C++ how would I go about getting a specific line from a text file and storing that in a char vector?

时光毁灭记忆、已成空白 提交于 2020-01-03 02:43:07

问题


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:


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.



来源:https://stackoverflow.com/questions/5206824/in-c-how-would-i-go-about-getting-a-specific-line-from-a-text-file-and-storing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!