2013-03-01 61 views
0
#include <iostream> 
#include <string> 
#include <cstring> 
#include <fstream> 
using namespace std; 

int main() { 

string firstFile, secondFile, temp; 

ifstream inFile; 
ofstream outFile; 

cout << "Enter the name of the input file" << endl; 
cin >> firstFile; 

cout << "Enter the name of the output file" << endl; 
cin >> secondFile; 

inFile.open(firstFile.c_str()); 
outFile.open(secondFile.c_str()); 

while(inFile.good()) { 

    getline(inFile, temp, ' '); 

     if ( temp.substr(0,4) != "-----" 
      && temp.substr(0,5) != "HEADER" 
      && temp.substr(0,5) != "SUBID#" 
      && temp.substr(0,5) != "REPORT" 
      && temp.substr(0,3) != "DATE" 
      && temp    != "" 
      && temp    != "") 
     { 
      outFile << temp; 
     } 
} 

inFile.close(); 
outFile.close(); 

return 0; 
} 

大家好。我試圖從文本文件中輸出所有不符合控制結構中的條件的行 - 即沒有空行,沒有符號等。但是,當我運行此代碼時,它會輸出所有內容,而不會考慮我的具體要求。如果有人能告訴我我做錯了什麼,將不勝感激。getline收到的過濾器輸入

+1

首先,你不應該循環'而(inFile.good())'。而是使用'while(getline(...))'。 – 2013-03-01 15:07:24

+0

你想處理線條或文字嗎? – Slava 2013-03-01 15:10:00

回答

1

如果你看一個參考such as this你會看到substr的第二個參數是字符數不是結束位置。

這意味着例如temp.substr(0,5)可能會返回"HEADE",這確實不等於"HEADER"。這意味着將輸出所有非空字符串。

還要注意的是,現在,你實際上並沒有讀你的空間分隔輸入。

0

當你重複同樣的動作多次,這就是你需要一個函數的標誌:

bool beginsWith(const std::string &test, const std::string &pattern) 
{ 
    if(test.length() < pattern.length()) return false; 
    return test.substr(0, pattern.length()) == pattern; 
} 

你可以單獨測試它的第一,那麼你的條件將更加simplier且容易出錯少:

if (!beginsWith(temp, "-----") 
     && !beginsWith(temp, "HEADER") 
     && !beginsWith(temp, "SUBID#") 
     && !beginsWith(temp, "REPORT") 
     && !beginsWith(temp, "DATE") 
     && temp != "") 
0

短版(C++ 11):

const std::vector<std::string>> filter { 
    {"-----"}, {"HEADER"}, ... }; // all accepted line patterns here 

while(getline(inFile, temp)) { 
    for(const auto& s: filter) 
     if (s.size() == temp.size() && 
      std::equal(s.begin(), s.end(), temp.begin())) 

      outFile << temp;