【问题标题】:Reading tab delimeted files in c++ [duplicate]在c ++中读取制表符分隔的文件[重复]
【发布时间】:2014-10-18 15:23:58
【问题描述】:

我正在做一个项目,真的需要一些帮助。我已将变量存储到一个文件中,如下所示,但用制表符分隔它们。现在我想将它们作为单个变量读回,所以问题是,我如何在没有标签的情况下读取它们?我需要解析字符串吗?

void fileManagement::appendCustomeRFile(const Customer &obj)
{
  if(tryFile(CFile))
  {
    ifstream cfile(CFile);
    cfile<<obj.ReturnCustomerId()<<"\t"<<obj.ReturnFName()<<"\t"<<obj.ReturnLName()<<"\t"<<obj.ReturnContactNumber()<<"\t"<<obj.RetrunBalance()<<"\n\r";
    cfile.close;
  }
}

这就是我目前从文件中读取的方式。

void viewCustomerInfo(string contact_N)//
{
 tryFile(CFile);
 bool found=false;
 string retreivedId,retreivedFname, retreivedLname, retreivedNumber;
 double retreivedBalance;
 ofstream cfile(CFile);
 if(cfile.is_open())
  {
    while(!cfile.eof())
    {
        cfile>>retreivedId>>retreivedFname>>retreivedLname>>retreivedNumber>>retreivedBalance;
        if (retreivedNumber==contact_N)
        {
            found=true;
            cout<<"_______________________________________CUSTOMER INFO_______________________________________\n"<<"Customer ID: "<<retreivedId<<"\nFirst Name: "<<retreivedFname<<"\nLast Name: "<<retreivedLname<<"\n";
            cout<<"Contact Number: "<<retreivedNumber<<"\nCustomer Balance"<<retreivedBalance<<endl;
            cout<<"___________________________________________________________________________________________"<<endl;
            break;
        }
     }
   }
}

非常感谢任何帮助。谢谢。

【问题讨论】:

  • 我建议使用分词器,要么自己写一个,要么用谷歌搜索一个(例如:boost 包括一个)
  • 不要使用eof。使用eof 总是错误的。
  • 使用来自 boost 项目的库,boost tokenizer,boost.2283326.n4.nabble.com/tokenizing-a-string-td2564907.html
  • 我会使用std::getline(cfile, retreivedFname, '\t');。它将获取所有内容(但不包括)选项卡,但它会从输入中提取选项卡。
  • 请在发帖前搜索 StackOverflow。关于逗号分隔值 (CSV) 或制表符分隔文件的问题太多了。您可以通过搜索“c++ read text columns from file”获取更多示例。

标签: c++ file parsing delimiter string-parsing


【解决方案1】:

而不是做

while(!cfile.eof())

试试这个

 while(cfile>>retreivedId>>retreivedFname>>retreivedLname>>retreivedNumber>>retreivedBalance)

【讨论】:

    猜你喜欢
    • 2010-11-07
    • 2020-06-18
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    相关资源
    最近更新 更多