且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中,我将如何从一个文本文件获取一个特定的行并将其存储在一个char向量?

更新时间:2023-11-21 23:33:22

只读所有行,忽略您不感兴趣的行:

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.

此外,我真的不知道什么char向量/ array是for。使用 std :: string 为您的字符串处理需求,这是它的作用。

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.