I have a problem with my code? (C++)?

I think I have a logical problem with my C++ code, but I can't figure it out. I am trying to figure out this question:http://wcipeg.com/problem/ccc02j2

#include <iostream>

#include <string>

using namespace std;

int main()

{

string am;

cin>>am;

int consonant=0;

int position;

while(am!="quit!"){

for(int i=0;i<am.length();i++){

if(am[i]=='o'&&am[i+1]=='r'){

consonant=2;

position=i+1;

}

}

if(am.length()>4&&consonant==2){

am.insert(position,"u");

cout<<am<<endl;

}

else{

cout<<am<<endl;

}

cin>>am;

}

return 0;

}

2 Answers

Relevance
  • 5 years ago
    Favorite Answer

    I do not understand most of your code. However, the most obvious mistake that I could find is in the line: if(am[i]=='o'&&am[i+1]=='r')

    Since you are iterating over the entire length of the input string, i+1 at the last character would cause out of bound access of the array.

    My attempt at the code is this: http://ideone.com/oQ3Vxu

    For any further help, feel free to email me at anas_imtiaz@yahoo.com

  • 5 years ago

    Oh my.

    The problem doesn't say to do anything with "or" except at the end.

    Consonants are letters that aren't vowels. A very simple way to detect them is to search a list of vowels, producing (true) as a result if the character is not found.

    const string vowels = "aeiouy"; // put this at the start of main()

    A char c is a consonant if it is not in that string. In C++:

    if (vowels.find(c) == string::npos)

    { it's a consonant }

    "If the word has more than four letters and has a suffix consisting of a consonant followed by 'or'" says that three separate conditions must all be true. It's a long condition written as the and of those tree tests, so I'd nest the slower, more complicated one:

    size_t n = word.length(); // number of characters in the the word

    if (n>4 && word.subtstring(n-2)=="or")

    {

    .... if (string::npos == vowels.find(word[n-3]))

    .... {

    .... .... // It's American

    .... }

    }

    You could add that third condition, "and-ed" with &&,. to make one big if statement, if you like. Either way, test for n>4 first so that the other tests will have valid index values. C++ && operations won't evaluate the right operand if the left side is false.

    The .... tokens are for visible indentation. Pretend they are spaces or tabs. (Y!A strips all leading whitespace and compresses internal whitespace strings to single spaces.)

    You are correct to use .insert() to add a 'u' to the spelling, but the position is always (n-1).

Still have questions? Get your answers by asking now.