在C ++

时间:2018-09-27 20:02:43

标签: c++ file-io fstream

现在,我正在尝试阅读一列具有制表符分隔信息的书籍列表,仅打印标题。最终,我会将每条信息及其名称添加到向量中。当我将分隔符从一个字符空间或一个字符空间切换到一个选项卡时,突然没有任何输出。我查看了堆栈交换,但是大多数这些解决方案都没有告诉我为什么我的代码不起作用。 这是我的代码

#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;

}

输入文件的前两行:

1876    Gore Vidal    Random House    4/11/1976    Fiction
23337    Stephen King    Scribner    11/27/2011    Fiction

1 个答案:

答案 0 :(得分:0)

有一段代码可以正确读取您的文件示例,并输出到stdout。请注意,“ getline”功能中使用了定界符:制表符(字符“ \ t”)用于标记数据字段的结尾,而换行符“ \ n”用于标记行尾。检查您的数据文件,看它是否确实包含制表符分隔符。 “窥视”功能检查流中的下一个字符,如果没有更多的字符,它将设置流的“ eof”标志。因为可能有更多条件可能会使读取流无效,所以我将good()函数用作“ while”循环中的条件。

#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)
*/