现在,我正在尝试读取一个图书列表,其中包含制表符分隔的信息,并且只打印标题。最后,我会将每条信息添加到一个带有它们的名称的向量中。以下是我的代码
#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发布于 2019-03-03 18:50:56
有一段代码可以正确读取您的文件示例并打印到stdout。请注意'getline‘函数中使用的分隔符:制表符(字符'\t')用于标记数据字段的结尾,换行符'\n’用于标记行尾。检查你的数据文件,看看它是否包含制表符分隔符。'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)
*/https://stackoverflow.com/questions/52544338
复制相似问题