简体   繁体   English

在 C++ Builder 中获取文本文件的第二行

[英]Get the second line of a Text File in C++ Builder

My text file looks like this我的文本文件看起来像这样

Fruit 
Vegetable

And I need the function to return Vegetable我需要 function 来返回Vegetable

This is the code I tried to use and get "Vegetable":这是我尝试使用并获得“蔬菜”的代码:

String getItem()
{
ifstream stream("data.txt");

stream.ignore ( 1, '\n' );

std::string line;
std::getline(stream,line);

std::string word;
return word.c_str();
} 

Then I did this to try and put the second line into an edit box:然后我这样做是为了尝试将第二行放入编辑框中:

void __fastcall TMainForm::FormShow(TObject *Sender)
{
    Edit1->Text = getItem();
}

For some reason, when I run the code the Edit Box eventually just has nothing in it, completely blank.出于某种原因,当我运行代码时,编辑框最终什么都没有,完全空白。

The 1st parameter of istream::ignore() is expressed in characters , not lines . istream::ignore()的第一个参数以字符而不是表示。 So, when you call stream.ignore(1, '\n') , you are ignoring only 1 character (ie, the F of Fruit ), not 1 line .因此,当您调用stream.ignore(1, '\n')时,您只会忽略1 个字符(即FruitF ),而不是1 line

To ignore a whole line, you need to pass in std::numeric_limits<streamsize>::max() instead of 1 .要忽略整行,您需要传入std::numeric_limits<streamsize>::max()而不是1 That tells ignore() to ignore all characters until the specified terminator ( '\n' ) is encountered.这告诉ignore()忽略所有字符,直到遇到指定的终止符 ( '\n' )。

Also, you are return 'ing a blank String .此外,您将return一个空白String You are ignoring the line that you read with std::getline() .您忽略了使用std::getline()阅读的line

Try this instead:试试这个:

#include <fstream>
#include <string>
#include <limits>

String getItem()
{
    std::ifstream stream("data.txt");

    //stream.ignore(1, '\n');
    stream.ignore(std::numeric_limits<streamsize>::max(), '\n');

    std::string line;
    std::getline(stream, line);

    return line.c_str();
    // or: return String(line.c_str(), line.size());
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM