在C ++中,我将如何从一个文本文件获取一个特定的行并将其存储在一个char向量? [英] In C++ how would I go about getting a specific line from a text file and storing that in a char vector?
问题描述
我想让我的程序打开一个文本文件,下到一个特定的行(例如,第18行),并将该行上的每个字符存储在一个char向量中。
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)获取特定行和将其存储在字符串中
1) Get specific line and store it in a string
2)将该字符串转换为char向量。我使用一个向量而不是一个数组,所以我可以使用pushback()使向量所需的精确大小,而不是在数组中分配太多或太少。
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.
我可以做第2步很好,但它是第1步我有麻烦。我如何让它去一个特定的行?
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?
推荐答案
只读所有行,忽略您不感兴趣的行:
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.
这篇关于在C ++中,我将如何从一个文本文件获取一个特定的行并将其存储在一个char向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!