I'm trying to search a specified file for all instances of substring "abbaa."
This is an easy problem, and I know I can do it better than I have, but the professor is making us use a 6x3 array in order to help us understand finite state machines.
Well the code I wrote runs perfectly, but the case for '\n' doesn't catch. It just flows through without it. Any ideas? (it's probably something extremely simple)
Thanks in advance!
Significant portion of code:
Code:if(fin) { fin >> inChar; while(fin) { switch(inChar) { case 'a': currentState = state[currentState][a]; break; case 'b': currentState = state[currentState][b]; break; case '\n': lineCount++; colCount = 0; currentState = state[currentState][other]; break; default: currentState = state[currentState][other]; break; } fin >> inChar; if(currentState == S5) cout << endl << "* line " << lineCount << ", column " << colCount - 4; colCount++; } quit = true; }
Program:
Note: I know this code is pretty sloppy, but I've done it in just a few hours (most of which was trying to solve this bug). I will tidy it up later.Code:#include <iostream> #include <fstream> #include <string> using namespace std; int main() { //declerations and definitions enum { S0, S1, S2, S3, S4, S5 }; enum { a, b, other }; fstream fin; string file; char inChar; bool quit = false; int state[6][3], //6x3 array for state currentState = S0, lineCount = 1, colCount = 1; /* currentState = &state[*currentState][a]; cout << *currentState; */ //define the array for(int i = S0; i <= S5; i++) state[i][other] = S0; state[S0][a] = S1; state[S1][a] = S1; state[S2][a] = S1; state[S3][a] = S4; state[S4][a] = S5; state[S5][a] = S1; state[S0][b] = S0; state[S1][b] = S2; state[S2][b] = S3; state[S3][b] = S0; state[S4][b] = S2; state[S5][b] = S2; while(quit == false) { //open the fin stream cout << "Please enter the input file:" << endl << "* "; cin >> file; fin.open(file,ios::in); //check for fin stream if(fin) { fin >> inChar; while(fin) { switch(inChar) { case 'a': currentState = state[currentState][a]; break; case 'b': currentState = state[currentState][b]; break; case '\n': lineCount++; colCount = 0; currentState = state[currentState][other]; break; default: currentState = state[currentState][other]; break; } fin >> inChar; if(currentState == S5) cout << endl << "* line " << lineCount << ", column " << colCount - 4; colCount++; } quit = true; } else { do { system("CLS"); cout << "The input file was not opened successfully. Would you like to try again?" << endl << "(y/n):" << endl << "* "; cin >> inChar; inChar = toupper(inChar); } while(inChar != 'Y' && inChar != 'N'); if(inChar == 'N') quit = true; system("CLS"); } } cout << endl << endl; system("PAUSE"); return 0; }
Note2: When I get better at coding I plan to contribute to this community instead of just asking questions all of the time!




)
Reply With Quote