读取制表符分隔的文件时出现问题 C++
Problem reading a tab delimited file in C++
现在我正在尝试阅读具有制表符分隔信息的书籍列表,并且只是打印标题。最终,我将每条信息添加到带有其名称的向量中。当我将分隔符从无或一个字符空格切换到制表符时,突然没有输出任何内容。我已经查看了堆栈交换,但是这些解决方案中的大多数都没有告诉我为什么我的解决方案不起作用。 这是我的代码
#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)
*/
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题