首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C++中读取制表符分隔的文件时出现问题

在C++中读取制表符分隔的文件时出现问题
EN

Stack Overflow用户
提问于 2018-09-28 04:02:43
回答 1查看 873关注 0票数 0

现在,我正在尝试读取一个图书列表,其中包含制表符分隔的信息,并且只打印标题。最后,我会将每条信息添加到一个带有它们的名称的向量中。以下是我的代码

代码语言:javascript
复制
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;

int main() {
ifstream DataFile;
string str;
string title;
string author;
string publisher;
string date;
string ficornon;

if(!DataFile)
{
    cout<<"error";

}
DataFile.open("/Users/Kibitz/Desktop/bestsellers.txt",ios::in);
getline(DataFile,title);
while(!DataFile.eof()) // To get you all the lines.
{

    cout<<title<<endl;
    getline(DataFile,author);
    getline(DataFile,publisher);
    getline(DataFile,date);
    getline(DataFile,ficornon);
    getline(DataFile,title);
}
DataFile.close();
return 0;

}

输入文件的前两行:

代码语言:javascript
复制
1876    Gore Vidal    Random House    4/11/1976    Fiction
23337    Stephen King    Scribner    11/27/2011    Fiction
EN

回答 1

Stack Overflow用户

发布于 2019-03-03 18:50:56

有一段代码可以正确读取您的文件示例并打印到stdout。请注意'getline‘函数中使用的分隔符:制表符(字符'\t')用于标记数据字段的结尾,换行符'\n’用于标记行尾。检查你的数据文件,看看它是否包含制表符分隔符。'peek‘函数检查流中的下一个字符,如果没有更多的字符,则设置流的'eof’标志。因为可能有更多的条件可以使读取的流无效,所以我使用good()函数作为'while‘循环中的条件。

代码语言:javascript
复制
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;   

int main() {
std::ifstream DataFile;
string str;
string title;
string author;
string publisher;
string date;
string ficornon;

  DataFile.open("bestsellers.txt",std::ifstream::in);
// getline(DataFile,title);  // don't need this line
  DataFile.peek(); // try state of stream
  while(DataFile.good())  
  {
    getline(DataFile,str,  '\t');     // you should specify tab as delimiter between filelds
    getline(DataFile,author, '\t');   // IMO, better idea is to use visible character as a delimiter, e.g ','  or ';' 
    getline(DataFile,publisher, '\t');
    getline(DataFile,date,'\t');
    getline(DataFile,ficornon,'\n');   // end of line is specified by '\n'
    std::cout << str << " " << author << " " << publisher <<  " " << date << " " << ficornon << std::endl;
    DataFile.peek(); // set eof flag if end of data is reached
  }

  DataFile.close();
  return 0;
}
/*
Output:
1876 Gore Vidal Random House 4/11/1976 Fiction
23337 Stephen King Scribner 11/27/2011 Fiction
(Compiled and executed on Ubuntu 18.04 LTS)
*/
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52544338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档