Skip to main content
gamedev.net
🔒 Locked

state machine help needed please

Started by angelxe1 3 replies 650+ views
Original Post
angelxe1
angelxe1
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 #include #include 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 == ' ' || ch == '\n')) {sp++; i++;} if (spState && (ch != ' ' || ch != '\n')) { spState = false; wrdState = true; word++; nonBlank++; i++; } if (wrdState && (ch != ' ' || ch != '\n')) {nonBlank++; i++;} if (wrdState && (ch == ' ' || ch == '\n')) { sp++; i++; spState = true; wrdState = false;} } } cout << "spaces = " << sp << endl; cout << "words = " << word << endl; cout << "non-blank = " << nonBlank << endl; fin.close(); }
Cocalus
Cocalus
The most glaring thing I see is that (ch != ' ' || ch != '\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.
angelxe1
angelxe1
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 != ' ' & ch != '\n')
but that makes my nonblank 49 and it should be 54.
Cocalus
Cocalus
You want (ch != ' ' && ch != '\n') or !(ch == ' ' || ch == '\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.
angelxe1
angelxe1
thank you i figured it out from your clue!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.