Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <vector>
- using namespace::std;
- // prints all English words which are contiguous substrings of inputtedWord into a file
- void embeddedWords( vector< char > &dictionaryWord, vector< char > &inputtedWord );
- // returns true if and only if dictionaryWord is a substring of inputtedWord
- bool isSubstring( vector< char > &dictionaryWord, vector< char > &inputtedWord );
- int main()
- {
- vector< char > inputtedWord;
- cout << "Enter a word: ";
- char ch = cin.get();
- while( ch != '\n' )
- {
- inputtedWord.push_back( ch );
- ch = cin.get();
- }
- vector< char > dictionaryWord;
- embeddedWords( dictionaryWord, inputtedWord );
- system( "pause" );
- }
- void embeddedWords( vector< char > &dictionaryWord, vector< char > &inputtedWord ){
- ifstream infiletext("Dictionary.txt", ifstream::in);
- ofstream outfiletext("word.txt",ofstream::out);
- if(!infiletext){ //載入失敗
- cout<<"error"<<endl;
- }
- else{ //載入成功
- while(!infiletext.eof()){
- char ch=infiletext.get(); //放入第一個字元
- dictionaryWord.clear();
- if (infiletext.fail()) //解決最後有空白數據的bug
- break;
- while(ch!='\n'){
- dictionaryWord.push_back(ch);
- ch=infiletext.get();
- }
- if(dictionaryWord.size()<=inputtedWord.size() && isSubstring(dictionaryWord,inputtedWord)){
- for(int i=0;i<dictionaryWord.size();i++){ //印出
- cout<<dictionaryWord[i];
- outfiletext<<dictionaryWord[i];
- }
- cout<<endl;
- outfiletext<<endl;
- }
- }
- }
- }
- bool isSubstring( vector< char > &dictionaryWord, vector< char > &inputtedWord ){
- for(int i=0;i<=inputtedWord.size()-dictionaryWord.size();i++){ //起點做到兩者字串長度相減
- bool flag=true;
- for(int j=0;j<dictionaryWord.size();j++)
- if(dictionaryWord[j]!=inputtedWord[i+j]){ //非子字串時換起點且此段並非子字串
- flag=false;
- break;
- }
- if(flag) //上續完全正確,此段為子字串,結束跳出並return true
- return true;
- }
- return false; //上續沒有一段為子字串,結束跳出並return false;
- }
Add Comment
Please, Sign In to add comment