Replacing Consonants

I've been trying to code a program that lets you enter a sentence, or merely a word or letter if desired, and then outputs that string but with all of the consonants replaced. As an example if you enter an "r" the program should output "ror", and it should also replace "b" with "bob". Don't ask me why by the way.

Anyway, somehow the program ***** up, it still runs, but outputs seemingly strange error messages. An an example, this is one of the error messages I got:

Enter a sentence: hejsan
Your sentence, but now translated: tribang::compareic_string::compareeg::compareing::copyejsan


Could someone take a look at my code and help me with finding out what's wrong? Because something clearly is...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

string translator(string first){
    char konsonanter[] = "bcdfghjklmnpqrstvxyzBCDFGHJKLMNPQRSTVXYZ";
    int n1 = first.size();
    for(int x=0;x<n1;x++){
        for(int y=0;y<42;y++){
            if(first[x]==konsonanter[y]){
                first.erase(x, 1);
                first.insert(x, (konsonanter[y] + "o" + konsonanter[y]));
                break;
            }
        }
    }
    return first;
}

int main(){
    string sentence, ny;
    cout << "Enter a sentence: "; getline(cin, sentence);
    ny = translator(sentence);
    cout << "Your sentence, but now translated: " << ny;
}
In line 5, konsonanter[] has only 40 characters not 42 as is assumed in line 8.
Last edited on
the code you posted wasn't compiled, it has errors.
getline() isn't used like this, you should either include the cstdio library (not recommended), or ou should use:
istream& operator>> ( istream&, string& )
this is the main function as it should be:

1
2
3
4
5
6
7
int main(){
    string sentence, ny;
    cout << "Enter a sentence: ";
    cin>>sentence;  //use the overloaded extractor rather than getline.
    ny = translator(sentence);
    cout << "Your sentence, but now translated: " << ny <<endl;
}


the output is weird, but i don't know what's your point in this program, maybe this is how you want it.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::string translator( std::string s )
{
	const char konsonanter[] = "bcdfghjklmnpqrstvxyzBCDFGHJKLMNPQRSTVXYZ";

	for ( std::string::size_type pos = s.find_first_of( konsonanter, 0 );
		  pos != std::string::npos; 
		  pos = s.find_first_of( konsonanter, pos ) )
	{
		char inserter[] = "o?";
		inserter[1] = s[pos];

		s.insert( pos + 1, inserter );
		pos += sizeof( inserter );
	}

	return s;
}
Topic archived. No new replies allowed.