簡體   English   中英

在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”)用於標記數據字段的結尾,而換行符“ \\ 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)
*/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM