C++ 读取一行文件c++;

C++ 读取一行文件c++;,c++,file,fstream,C++,File,Fstream,我只是想使用流媒体库,我想读一行。 我想过这个,但我不知道这是不是最有效的方法 #include <iostream> #include <fstream> using namespace std; int main(){ int x; fstream input2; string line; int countLine = 0; input2.open("theinput.txt"); if(input2.is_open(

我只是想使用流媒体库,我想读一行。 我想过这个,但我不知道这是不是最有效的方法

#include <iostream>
#include <fstream>
using namespace std;
int main(){
    int x;
    fstream input2;
    string line;
    int countLine = 0;
    input2.open("theinput.txt");
    if(input2.is_open());
        while(getline(input2,line)){
            countLine++;
            if (countLine==1){ //1 is the lane I want to read.
                cout<<line<<endl;
            }

        }
    }

}
#包括
#包括
使用名称空间std;
int main(){
int x;
fstream输入2;
弦线;
int countLine=0;
input2.open(“theinput.txt”);
如果(input2.is_open());
while(getline(input2,line)){
countLine++;
如果(countLine==1){//1是我想读的通道。

cout我想你可以把你的代码压缩成这样。
如果(输入)
足以检查失败

#include <iostream>
#include <fstream>
#include <limits>

int main()
{
    std::ifstream input("file.txt");
    int row = 5;
    int count = 0;
    if (input)
    {
        while (count++ < row) input.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::string line;
        std::getline(input, line);
        std::cout << line;
    }
}
#包括
#包括
#包括
int main()
{
std::ifstream输入(“file.txt”);
int行=5;
整数计数=0;
如果(输入)
{
while(count++std::cout这似乎不是最有效的代码,不是

特别是,您当前正在读取整个输入文件,即使您只关心文件中的一行。不幸的是,做好跳过一行的工作有些困难。不少人建议使用以下代码:

your_stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
根据具体情况,您可能更愿意将最大行大小作为参数传递(可能带有默认值):

有了它,您可以在默认情况下最多跳过一兆字节,但如果您想指定不同的最大值,您可以非常轻松地做到这一点

不管是哪种方式,定义了它,剩余部分都变得相当微不足道,如下所示:

bool skip_line(std::istream &in) { 
    size_t max = 0xfffff;

    in.ignore(max, '\n');
    return in.gcount() < max;
}
int main(){  
    std::ifstream in("theinput.txt");

    if (!skip_line(in)) {
        std::cerr << "Error reading file\n";
        return EXIT_FAILURE;
    }

    // copy the second line:
    std::string line;
    if (std::getline(in, line))
        std::cout << line;
}

这样一来,你就失去了确保你的输入是你所期望的,并且不会产生垃圾的一个基本好处。

如果(input2.is_open());
是多余的,有分号和没有分号。哦,谢谢,我从指南中选取了这部分。我知道我可以删除,但无论如何,谢谢。
int main(){  
    std::ifstream in("theinput.txt");

    if (!skip_line(in)) {
        std::cerr << "Error reading file\n";
        return EXIT_FAILURE;
    }

    // copy the second line:
    std::string line;
    if (std::getline(in, line))
        std::cout << line;
}
for (int i=0; i<lines_to_skip; i++)
    skip_line(in);