URGENT!!!this program runs but it has a problem

program no.1 ==this program should accept both string and a single character from the user. The program should determine how many times the character is contained in the string.==

#include <iostream>
#include <conio.h>
#include <string>

using namespace std;

int main()
{
string str;
char chr;
int i=0, ctr=0;

cout << "Enter a string: ";
getline(cin, str);

cout << "Enter a charter: ";
cin >> chr;

while (i < str.length())
{
if (i = str.find(chr))
ctr++;
i++;
}
cout << "There are " << ctr << chr << "in the string " << endl;

getch();
return 0;
}


program no.2 == This program accepts a string from the user and then replaces all occurrences of the letter "e" with the letter "x".

#include <iostream>
#include <conio.h>
#include <string>

using namespace std;

int main()
{
string str;
int i=0;

cout << "Enter a string:";
getline (cin, str);

while (i < str.length())
{
i= str.find("e");
str.replace(i, 1, "x");
i++;
}
cout << str <<endl;

return 0;
}


Hi,

In your first program i = str.find(chr) will return the first occurence of the character in the string.

Now the while loop will never end in case where character is at found in any location other than last location.
Last edited on
Program 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::cout << "Enter a string: ";
    std::string str;
    std::cin >> str;

    std::cout << "Enter a charter: ";
    char ch;
    std::cin >> ch;

    std::cout << "We found the symbol '" << ch << "' in string '" << str << "' " <<
        std::count(str.begin(), str.end(), ch) << " times\n";

    return 0;
}

Program 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::cout << "Enter a string:";
    std::string str;
    std::cin >> str;

    std::string::iterator end(str.end());
    std::string::iterator it(std::find(str.begin(), end, 'e'));
    while (it != end)
    {
        *it = 'x';
        it = std::find(str.begin(), end, 'e');
    }
    
    std::cout << str << '\n';

    return 0;
}
@ankushnandan
@Denis

thanks to your help guys! it's a success! :)
Topic archived. No new replies allowed.