繁体   English   中英

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

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

我的文本文件看起来像这样

Fruit 
Vegetable

我需要 function 来返回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();
} 

然后我这样做是为了尝试将第二行放入编辑框中:

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

出于某种原因,当我运行代码时,编辑框最终什么都没有,完全空白。

istream::ignore()的第一个参数以字符而不是表示。 因此,当您调用stream.ignore(1, '\n')时,您只会忽略1 个字符(即FruitF ),而不是1 line

要忽略整行,您需要传入std::numeric_limits<streamsize>::max()而不是1 这告诉ignore()忽略所有字符,直到遇到指定的终止符 ( '\n' )。

此外,您将return一个空白String 您忽略了使用std::getline()阅读的line

试试这个:

#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