Program doesn't respond.

The program should find all the 'a' letters in a string and replace it with 'e'.
However, I do not get any response...

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>
#include <string>

using namespace std;

int main()
{
    string naam;

    cout<<"Geef je naam in: ";
    cin>>naam;

    int letter;

    for (; letter != string::npos;);
    {
        letter = naam.find("a");
        naam.replace(letter, 1, "e");

    }
    cout<<naam;
    system("pause");

}
You didn't assign any value to letter, so your program can't use it's value in expression. Try with this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
using namespace std;

int main() {
	cout << "Type 'axit' to exit the program :)\n\n";
	for(;;) {
		string text;
		cout << "Your text: ";
		cin >> text;
		for(int i=0; i<(int)text.size(); ++i)
			if(text[i]=='a')
				text[i] = 'e';

		if(text == "exit") return 0;
		cout << "Changed: " << text << endl;
	}
}


EDIT: I'm not familiar with how string::npos (and replace) works. If you don't have long texts, I'd just use the loop. I think replace most likely does similar thing anyway.
Last edited on
Firstly, use getline() when working with strings: http://www.cplusplus.com/reference/string/getline/

Secondly, you're for loop contains no initialization, and does no inc/decrementing. So would it not make sense to use a while loop that only uses a condiotion?

Thirdly, you're not chaning the starting position of the where you start the search in your string so if there is more than one 'a' you won't find them; you'll just keep finding thrat first 'a'.

Lastly, you have a semi-colon on line 15 that actually makes it look like your program has frozen, but it has actualyl entered an infinite loop.
Topic archived. No new replies allowed.