【问题标题】:Get the second line of a Text File in C++ Builder在 C++ Builder 中获取文本文件的第二行
【发布时间】:2020-07-20 03:22:19
【问题描述】:

我的文本文件是这样的

Fruit 
Vegetable

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

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

【问题讨论】:

  • getItem() 返回一个空字符串。 word 永远不会填充任何内容。 std::string word; 行上方的所有内容都是精心设计的无操作。
  • ignore 调用只搜索接下来的 1 个字符,这还不够。我不知道你为什么不直接打电话给getline 两次就可以了。
  • ifstream 流("data.txt"); std::string 行;标准::getline(流,线);标准::getline(流,线);返回 line.c_str();像那样?返回第一行
  • 什么?是的,但不是:第二次调用将用第二行输入覆盖字符串,假设它成功了。 String 的数据类型是什么?这是您自己定义的,例如typedef char* String;?如果是这样,那么你的程序有未定义的行为,它永远不会那样工作。不要返回指向已销毁内存的指针。另外,不要在你自己编造的 typedef 中隐藏基本类型,比如指针。这会降低您的代码的可读性,并且更容易出现错误。
  • @paddy String 是 C++Builder 的默认 RTL 字符串类型的别名,在 C++Builder 2009 及更高版本中为 System::UnicodeString,在 C++Builder 中为 System::AnsiString 2007 年及之前

标签: c++ c++builder vcl


【解决方案1】:

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

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

另外,你是return'ing 一个空白的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());
} 

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多