2011-02-28 6 views
1

파일에서 읽으려고하고 파일에서 모든 단어의 벡터를 만들려고합니다. 내가 아래에서 시도한 것은 사용자가 파일 이름을 입력하게 한 다음 코드가 파일을 열고 영숫자가 아닌 문자를 건너 뛰고 파일에 입력하는 것입니다.파일에서 읽으려고하고 C++에서 구두점을 건너 뜁니다.

바로 지금 파일 이름을 입력하면 바로 닫힙니다. 내가 뭘 잘못했는지 알기나 해?

#include <vector> 
#include <string> 
#include <iostream> 
#include <iomanip> 
#include <fstream> 
using namespace std; 

int main() 
{ 

string line; //for storing words 
vector<string> words; //unspecified size vector 
string whichbook; 
cout << "Welcome to the book analysis program. Please input the filename of the book you would like to analyze: "; 
cin >> whichbook; 
cout << endl; 

ifstream bookread; 
//could be issue 
//ofstream bookoutput("results.txt"); 

bookread.open(whichbook.c_str()); 
//assert(!bookread.fail()); 

if(bookread.is_open()){ 
    while(bookread.good()){ 
     getline(bookread, line); 
     cout << line; 
     while(isalnum(bookread)){ 
      words.push_back(bookread); 
     } 
    } 
} 
cout << words[]; 
} 
+2

이 코드는 컴파일되지해야'words' 그래서'말은 [] '매개 변수 누락되는'표준 : : 벡터 '이다. ([이 링크] (http://www.cplusplus.com/reference/stl/vector/operator [] /)에 따르면 매개 변수를 사용하지 않는 과부하가 없음) – ereOn

+0

+1 to ereOn. 벡터'words'의 각 항목을 순환하여'cout'으로 출력하고 싶을 것입니다. – arviman

+0

이 줄'getline (bookread, line);이 실패하면 어떻게됩니까? 실패 여부는 확인하지 않습니다. –

답변

2

나는 조금 다르게 작업 할 것이라고 생각합니다. 당신이 영숫자를 제외하고 모두 무시해야하기 때문에, 나는 공백으로 다른 모든 문자를 취급 로케일을 정의하여 시작 했죠 : 단어를 읽는하게

struct digits_only: std::ctype<char> { 
    digits_only(): std::ctype<char>(get_table()) {} 

    static std::ctype_base::mask const* get_table() { 
     static std::vector<std::ctype_base::mask> 
      rc(std::ctype<char>::table_size,std::ctype_base::space); 

     std::fill(&rc['0'], &rc['9'], std::ctype_base::digit); 
     std::fill(&rc['a'], &rc['z'], std::ctype_base::lower); 
     std::fill(&rc['A'], &rc['Z'], std::ctype_base::upper); 
     return &rc[0]; 
    } 
}; 

/스트림에서 번호 아주 사소한. 예를 들어 : 순간

int main() { 
    char const test[] = "This is a bunch=of-words and [email protected]#4(with)stuff to\tseparate,them, I think."; 
    std::istringstream infile(test); 
    infile.imbue(std::locale(std::locale(), new digits_only)); 

    std::copy(std::istream_iterator<std::string>(infile), 
       std::istream_iterator<std::string>(), 
       std::ostream_iterator<std::string>(std::cout, "\n")); 

    return 0; 
} 

, 나는 표준 출력으로 단어/숫자를 복사했지만, 벡터에 복사는 std::copy에 다른 반복자를 제공하는 것을 의미한다. 실제 사용을 위해서는 의심 할 여지없이 std::ifstream에서 데이터를 가져오고 싶지만 정확한 반복기를 제공해야합니다. 파일을 열어서 로케일과 함께 붙이고 단어/숫자를 읽으십시오. 모든 구두점 등은 자동으로 무시됩니다.

0

다음은 모든 줄을 읽고 영문자가 아닌 문자를 건너 뛰고 각 줄을 출력 벡터에 항목으로 추가합니다. 라인이 아닌 단어를 출력하도록 조정할 수 있습니다. 숙제 문제와 같이 전체 솔루션을 제공하고 싶지 않았습니다.

#include <vector> 
#include <sstream> 
#include <string> 
#include <iostream> 
#include <iomanip> 
#include <fstream> 
using namespace std; 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    string line; //for storing words 
    vector<string> words; //unspecified size vector 
    string whichbook; 
    cout << "Welcome to the book analysis program. Please input the filename of the book you would like to analyze: "; 
    cin >> whichbook; 
    cout << endl; 

    ifstream bookread; 
    //could be issue 
    //ofstream bookoutput("results.txt"); 

    bookread.open(whichbook.c_str()); 
    //assert(!bookread.fail()); 

    if(bookread.is_open()){ 
     while(!(bookread.eof())){ 
      line = ""; 
      getline(bookread, line); 


      string lineToAdd = ""; 

      for(int i = 0 ; i < line.size(); ++i) 
      { 
       if(isalnum(line[i]) || line[i] == ' ') 
       { 
        if(line[i] == ' ') 
         lineToAdd.append(" "); 
        else 
        { // just add the newly read character to the string 'lineToAdd' 
         stringstream ss; 
         string s; 
         ss << line[i]; 
         ss >> s;    
         lineToAdd.append(s); 
        } 
       } 
      } 

      words.push_back(lineToAdd); 

     } 
    } 
    for(int i = 0 ; i < words.size(); ++i) 
    cout << words[i] + " "; 


    return 0; 
} 
관련 문제