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

Problem reading a tab delimited file in C++

本文关键字:问题 C++ 文件 制表符 分隔 读取      更新时间:2023-10-16

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

#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

有一段代码可以正确读取您的文件示例并打印到 stdout。请注意"getline"功能中使用的分隔符:制表符(字符"\t"(用于标记数据字段的结尾,换行符""用于标记行尾。检查您的数据文件,看看它是否确实包含制表符分隔符。 "peek"函数检查流中的下一个字符,如果没有更多的字符,它会设置流的"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)
*/