Sign in to follow this  
angelxe1

state machine help needed please

Recommended Posts

my program is supposed to count the number of non-blank characters, spaces and words in the text. In this program, a word is a series of consecutive letters, numbers, or special characters separated by one or more spaces on either side except at the beginning or end of a line. I am using a state machine. well everything works well except for one thing, there are supposed to be 11 words in the output and i get 12. not sure what is wrong but here is the code: #include <fstream> #include <string> #include <iostream> using namespace std; void main() { char ch[80]; int i, spState, wrdState, sp = 0, nonBlank = 0, word = 0; ifstream fin; fin.open ("program13b.dat"); while (fin.getline(ch, 80)) { cout << ch << endl; i = 0; int lenght = strlen(ch); spState = true; wrdState = false; while (i < lenght) { if (spState && (ch[i] == ' ' || ch[i] == '\n')) {sp++; i++;} if (spState && (ch[i] != ' ' || ch[i] != '\n')) { spState = false; wrdState = true; word++; nonBlank++; i++; } if (wrdState && (ch[i] != ' ' || ch[i] != '\n')) {nonBlank++; i++;} if (wrdState && (ch[i] == ' ' || ch[i] == '\n')) { sp++; i++; spState = true; wrdState = false;} } } cout << "spaces = " << sp << endl; cout << "words = " << word << endl; cout << "non-blank = " << nonBlank << endl; fin.close(); }

Share this post


Link to post
Share on other sites
The most glaring thing I see is that (ch[i] != ' ' || ch[i] != '\n') is not doing what you think it is. (hint it's always true).

Also you can put your code between
[ source]

[ /source]
minus the spaces, to make it more readable.

Also this should be in the For Begginers forum.

Share this post


Link to post
Share on other sites
i should have posted this in the other forum *emberrassmed* should i copy and paste and make a new thread in there?
it's always true...the only think i can think of is that it should be
(ch[i] != ' ' & ch[i] != '\n')
but that makes my nonblank 49 and it should be 54.

Share this post


Link to post
Share on other sites
You want (ch[i] != ' ' && ch[i] != '\n') or !(ch[i] == ' ' || ch[i] == '\n').
But if then else would be a lot cleaner of doing it. (I'd post an example but you'll learn more if you can work it out yourself).

If you still can't get it to work, Post your updated code and I'll debug that. Another thing to consider is how your states end, do you always end in wrdState or spState, and how would that affect your counts.

If you make a new thread post a note here. A mod could also move it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this