2015-07-03 3 views
0

Я пытаюсь написать программу, которая:
Ошибка пользовательского потока объекта?

разбирает текст, удаляет предварительно заданные (пунктуации) символов и создает в алфавитном порядке словарь, содержащий анализируемые слова из текста, которые затем отображаются на экран. От Бьярне Stroustup в C++ Программирование: Принцип и практика

Вот что я написал:

Chapter11Exercise7Execute.cpp

#include "stdAfx.h" 
#include "Chapter11Exercise7.h" 

const string endInput("x"); 

int main(){ 
try{ 
    // instantiate a PunctStream object and initialize it to: cin 
    PunctStream ps(cin); 
    // construct initial set of characters to be replaced with whitepace 
    ps.whitespace(","); 
    // set case sensitivity 
    ps.caseSensitive(false); 

    string word; 
    vector<string> dictionary; 
    do{ 
     cout << "Type a word\n>>"; 
     cin >> word; 

     createDictionary(ps, dictionary); 
     printDictionary(dictionary);    
    }while(word != endInput); 
}catch(exception& e){ 
    cerr << e.what() << endl; 
    getchar(); 
} 
return 0; 
} 

Chapter11Exercise7.h

#include "stdAfx.h" 
#ifndef _Chapter11Exercise7_H 
#define _Chapter11Exercise7_H 

class PunctStream{ 
public: 
    // constructors 
    PunctStream(istream& is): source(is), sensitive(true){ } 
    // member-functions 
    // creates a set of characters to be searched and replaced with whitespace 
    void whitespace(const string& s){white = s;}; 
    void addWhitespace(char c){white += c;}; 
    bool isWhitespace(char c); 
    // set case sensitivity 
    void caseSensitive(bool b){sensitive = b;}; 
    bool isCaseSensitive(){return sensitive;}; 
    // overwritten extraction operator 
    PunctStream& operator>>(string& s); 
    // operator that returns a bool value on success/failure of PunctStream object 
    operator bool(); 
private: 
    // stream containing text to be parsed 
    istream source; 
    // stringstream containing a parsed text 
    istringstream buffer; 
    // case sensitivity 
    bool sensitive; 
    // characters to be replaced with whitespace 
    string white; 
}; 
// Non-member functions 
void createDictionary(PunctStream& ps, vector<string>& d); 
void printDictionary(vector<string>& d); 
#include "Chapter11Exercise7V1.cpp" 
#endif 

Chapter11Exercise7.cpp

#include "Chapter11Exercise7.h" 

// Member functions definition 
bool PunctStream::isWhitespace(char c){ 
    for(size_t i; i < white.size(); i++) if (c == white[i]) return true; 
    return false; 
} 
// Overwritten operators definition 
PunctStream& PunctStream::operator>>(string& s){ 
    while(!(buffer >> s)){ 
    // if buffer bad() or source not food => return PunctStream object 
    // this is a pointe to the object in context 
    if(buffer.bad() || !source.good()) return *this; 
    buffer.clear(); 

    string line; 
    // get a line from source 
    getline(source, line); 
    // replace "white" characters in "line" 
    for(size_t i = 0; i < line.size(); ++i){ 
     if(isWhitespace(line[i])) line[i] = ' '; 
     // if case sensitivity is set => convert to lowercase 
     else if (!sensitive) line[i] = tolower(line[i]); 
    } 
    // initialize the stringstream buffer to "line" 
    buffer.str(line); 
    } 
    return *this; 
} 

PunctStream::operator bool(){ 
    // to return true: fail() and bas() should be unset, good()-set 
    return !(source.fail() || source.bad()) && source.good(); 
} 
// Non-member functions 
void createDictionary(PunctStream& ps, vector<string>& d){ 
    string word; 
    while(ps >> word) d.push_back(word); 

    sort(d.begin(), d.end()); 
} 

void printDictionary(vector<string>& d){ 
    for(size_t i = 0; i < d.size(); ++i) cout << d[i] <<'\n'; 
} 

Ошибка я получаю следующее:

1>------ Build started: Project: bjarneStroustroupC, Configuration: Debug Win32 ------ 
1> Chapter11Exercise7Execute.cpp 
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\istream(860): error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>' 
1>   with 
1>   [ 
1>    _Elem=char, 
1>    _Traits=std::char_traits<char> 
1>   ] 
1>   c:\program files (x86)\microsoft visual studio 10.0\vc\include\ios(176) : see declaration of 'std::basic_ios<_Elem,_Traits>::basic_ios' 
1>   with 
1>   [ 
1>    _Elem=char, 
1>    _Traits=std::char_traits<char> 
1>   ] 
1>   This diagnostic occurred in the compiler generated function 'std::basic_istream<_Elem,_Traits>::basic_istream(const std::basic_istream<_Elem,_Traits> &)' 
1>   with 
1>   [ 
1>    _Elem=char, 
1>    _Traits=std::char_traits<char> 
1>   ] 
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 

Я прочитал сообщение об ошибке, но он не звонит любой звонок. Любые идеи или советы приветствуются!

ответ

1

Это сообщение об ошибке, которое вы получите, если попытаетесь сделать копию объекта istream, так как istream s не могут быть скопированы. Я думаю, что это конкретно происходит здесь:

class PunctStream{ 
public: 
    PunctStream(istream& is): source(is), sensitive(true){ } 

private: 
    istream source; 
}; 

Здесь вы пытаетесь инициализировать элемент source данных, чтобы быть копией параметра входного потока is, следовательно, ошибка.

Чтобы исправить это, рассмотреть вопрос об изменении source быть istream& - ссылка на istream - вместо конкретного istream объекта.

Надеюсь, это поможет!

+0

Ответ вы снова поможете (я думаю, я не узнал из этой ошибки). Если бы я мог снова проголосовать за него. :) – Ziezi

Смежные вопросы