Reputation: 11
I am writing a program for class. It takes a sentence and translates it into pseudo japanese (uses english words but rearranges into grammatical order and adds suffixes to pertinent words).
The library is limited and we cannot use functions or arrays (low level class). In THIS case I enter the sentence:
"is man red" (without the quotes)
The program parses the words correctly. I.e. no spaces around each word.
Here is my code
if (word1 == "is")
{
question = "is-ka";
//If the second word is a subject, assign it and continue
//assigning the 3rd or 4th word as the object or adjective and kick out
//an error if not
if (word2 == string("man") || word2 == string("woman") || word2 == string("fish"))
{
subject = word2 + "-ga";
if (word3 == "man" || word3 == "woman" || word3 == "fish")
{
object = word3 + "-o";
sentence = subject + ' ' + object + ' ' + question;
cout << sentence << endl;
}
if (word3 == "red" || word3 == "short" || word3 == "strong")
{
adj = word3;
sentence = subject + ' ' + adj + ' ' + question;
cout << sentence << endl;
}
else
{
cout << "This is not a proper Eng-- sentence." << endl;
cout << "2 The sentence lacks a proper object." << endl;
}
}
I test if the first word is 'is' because that is the only question format we are given to use. Given it is a question I proceed to find the subject, object, and adjective that must be in the sentence for it to be grammatically correct.
The first and second conditional for "is man red" pass, but when the conditional for "is man red" tests if the third word is "red", it skips to the else statement and displays the error.
Why is the conditional skipping when it should be true?
Example of a run:
Enter an Eng-- sentence you would like to translate
is man red
These are the words collected
Spaces after the colons and period at end of word are added.
First word: is.
Second word: man.
Third word: red.
This is not a proper Eng-- sentence.
2 The sentence lacks a proper object.
I hope THIS is what you have all been actually asking for. Full code and compiled with input from above
Upvotes: 1
Views: 166
Reputation: 1511
The problem here is that word3
doesn't contain exactly what it seems to, in a particularly confusing way. The code which reads into it looks like this
//Word 3
while(userSent[index] != ' ' && index <= sentLength)
{
word3 += userSent[index];
index++;
}
The condition index <= sentLength
should be index < sentLength
because of the zero-based indexing of C++ strings. With the <=
the loop body is also appending the terminating zero byte from userSent
to word3
. You can see this is happening by checking word3.length()
. The extra 0 byte has no effect when printing the string using cout
's operator<<
but it does prevent the string comparing equal with "red"
.
Upvotes: 2