2016-09-01 75 views
-3

我遇到了一個問題,它是從包含空格的單詞和隨機的新行中讀取的。這裏是我的代碼:從文件中讀取空格和換行的單詞的C++

vector<string> _vecIgnoreWords; 
vector<string> _vecHungerGames; 

void readTextFile(char *fileNameHungerGames, vector<string>& _vecHungerGames){ 
    ifstream fileInHungerGames; 
    string newline; 

    fileInHungerGames.open(fileNameHungerGames); 
    if(fileInHungerGames.is_open()){ 
     while(getline(fileInHungerGames, newline)){ 
      stringstream iss(newline); 
      while(iss){ 
       iss >> newline; 
       if(!(isCommonWord(newline, _vecIgnoreWords))){ 
        _vecHungerGames.push_back(newline); 
        cout << newline << endl; 
       } 
      } 
     } 

     fileInHungerGames.close(); 
    } 

呼叫主:

string fileName = argv[2]; 
string fileNameIgnore = argv[3]; 
char* p = new char[fileNameIgnore.length() + 1]; 
memcpy(p, fileNameIgnore.c_str(), fileNameIgnore.length()+1); 
getStopWords(p, _vecIgnoreWords); 
char* hungergamesfile_ = new char[fileName.length() + 1]; 
memcpy(hungergamesfile_, fileName.c_str(), fileName.length()+1); 
readTextFile(hungergamesfile_, _vecHungerGames); 

停止詞無效:

void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords){ 
    ifstream fileIgnore; 
    string line; 
    fileIgnore.open(ignoreWordFileName); 
    if(fileIgnore.is_open()){ 
     while(getline(fileIgnore, line)){ 
      _vecIgnoreWords.push_back(line); 
     } 
    } 
    fileIgnore.close(); 
    return; 
} 

我的問題現在是,我對這個代碼的輸出最終像:

bread 
is 
is 
slipping 
away 

take 

我不是確定爲什麼我重複(是)和我使用字符串流時的空行?

我的輸出應該是這樣的:

bread 
is 
slipping 
away 
from 
me 

還略顯不那麼重要,但我while循環循環一次太多這就是爲什麼我有if(_vecHungerGames.size() == 7682)是有辦法解決的循環一旦太多這個循環?

文件例如:

bread is 
slipping away from me 
i take his hand holding on tightly preparing for the 
+0

請輸入文件的樣本添加到您的帖子。 –

+0

檔案是非常長的(整個飢餓遊戲書之一),但這裏是它的一部分的一個例子: –

+0

麪包是 從我身上滑落 我握住他的手緊緊準備 –

回答

1

嘗試更多的東西是這樣的:

#include <iostream> 
#include <vector> 
#include <string> 
#include <fstream> 
#include <sstream> 

std::vector<std::string> _vecIgnoreWords; 
std::vector<std::string> _vecHungerGames; 

void getStopWords(const char *filename, std::vector<std::string>& output) 
{ 
    std::ifstream file(fileName); 
    std::string s; 

    while (std::getline(file, s)) 
     output.push_back(s); 
} 

void readTextFile(const char *filename, std::vector<std::string>& output) 
{ 
    std::ifstream file(fileName); 
    std::string s; 

    while (file >> s) 
    { 
     if (!isCommonWord(s, _vecIgnoreWords)) 
     { 
      output.push_back(s); 
      std::cout << s << std::endl; 
     } 
    } 
} 

int main() 
{ 
    getStopWords(argv[3], _vecIgnoreWords); 
    readTextFile(argv[2], _vecHungerGames); 

    // use _vecHungerGames as needed... 

    return 0; 
} 
+1

讀取到臨時的'string'是沒用的,而(文件>> s)會做作者需要的 – Slava

+0

更好。更乾淨。 – blackpen

相關問題