Replacing all letters in a string with an asterisk

Hi all...I am still very new to functions and I am trying to take in a string of one or multiple words, convert all the letters in the string to asterisks, then output the proper number of asterisks with the original spaces intact. Any clues you can give me on where I am wrong (or perhaps the entire thing is wrong)? Thanks.

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;

void unsolvedWord(string phrase);
string phrase;

int main()
{
	
	cout << "Please enter a word ";
	getline(cin, phrase);
	unsolvedWord(phrase);
	cout << phrase << endl;

}

void unsolvedWord(string phrase)
{
	
	for (int x = 0; x < phrase.length(); x++)
		phrase[x] = '*';

}
closed account (SECMoG1T)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void unsolvedWord(string& phrase);//pass your argument by reference

///use conditions 

#include <cctype>
if(isalpha(phrase[x]))
   phrase[x] = '*';

//or turn to std algorithm
#include<algorithm>
void unsolvedWord(string& phrase)
{
 std::transform(phrase.begin(),phrase.end(),phrase.begin(),[](char& c)->void{ if(isalpha(c)) c='*';});
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
using namespace std;

void unsolvedWord(string phrase);
string phrase;

int main()
{
	
	cout << "Please enter a word ";
	getline(cin, phrase);
	unsolvedWord(phrase);

}

void unsolvedWord(string phrase)
{
	string phr = phrase;
	for (int x = 0; x < phr.length(); x++)
		phr[x] = '*';

        cout << phr << endl;

}


Either you could do this or pass it by reference:

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;

void unsolvedWord(string phrase);
string phrase;

int main()
{
	
	cout << "Please enter a word ";
	getline(cin, phrase);
	unsolvedWord(phrase);

}

void unsolvedWord(string& phrase)
{
	for (int x = 0; x < phrase.length(); x++)
		phrase[x] = '*';

        cout << phrase << endl;

}


Hope I could help with this simple solution.
closed account (SECMoG1T)
@shackener you missed this with the original spaces intact

this should work
1
2
3
4
5
6
7
8
void unsolvedWord(string& phrase)
{
	
	for (int x = 0; x < phrase.length(); x++)
              if(isalpha(phrase[x]))
		{phrase[x] = '*';}

}
Last edited on
Thank you very much for the responses! Hopefully one day when I understand what I am doing I will be able to answer questions on here as well. It works perfectly now.
Topic archived. No new replies allowed.