How to get a specific line from a .txt (C++)

时间:2016-02-12 19:42:58

标签: c++ iostream getline

I would like some help with getting the first line from a txt file called "test.txt", I have discovered the getline function however I am not sure why my code doesn't work or what I need to do. I would like to get the first line from the .txt file, but it prints "t" for some reason. Feel free to correct me as you please if I am not handling it correctly. This is the code I am using:

string FirstLine;
ifstream File("test.txt");
string line;

if (File)
{
    while (getline(File, line))
    {
        FirstLine = line[0];
    }

    File.close();
}
cout << FirstLine;

And this is the .txt file:

this is line 1

this is line 2

this is line 3

2 个答案:

答案 0 :(得分:2)

If you just want the first line:

string line;
getline(File, line);

Your first line of the file is then stored in line as a, you guessed it, string

To get all lines (line by line):

while(getline(File, line).good())
    //do something with line

答案 1 :(得分:0)

string FirstLine;
ifstream File("test.txt");
string line;

if (File)
{
    getline(File, line);
    FirstLine = line;
    File.close();
}
cout << FirstLine;

Is the absolute minimum changes you need to your code to make it do what you want to do. However, there is A LOT of room for improvement on the above code sample. For example, why create two strings, line, and FirstLine, just pass FirstLine to the getline() function. I just modified what you provided to highlight where the mistakes where. Hope this helps...