Cannot find a way to replace all the characters

write a program that reads in a line consisting of a student's name, social security number, user id, and password. the program outputs the string in which all the digits of the social security number, and all the characters in the password are replaced by x. (the social security number is in the form 000-00-0000, and the user id and the password do not contain any spaces) your program should not use the operator [] to access a string. use the appropriate functions described in table 7-1. c++

So far I have everything that I need, except for the password part. I cant figure out a way to replace the password with x's.

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
26
27
28
29
30
  #include <iostream>
#include <string>

using namespace std;

int main()
{
	string information;

	int name, ssn, userID, password;

	cout << "Enter a student's name, social security number(include dashes), user id, and password in one line:" << endl;
	getline(cin, information);
	cout << endl;

	name = information.find(' ', 0);

	ssn = information.find(' ', name + 1);
	information.replace(ssn + 1, 3, "xxx");
	information.replace(ssn + 5, 2, "xx");
	information.replace(ssn + 8, 4, "xxxx");

	userID = information.find(' ', ssn + 1);

	password = information.find(' ', userID + 1);

	cout << information << endl;
	system("pause");
	return 0;
}
You are going to need to calculate the length of what you have left in the string from the position of the start of the password.
Last edited on
Ok....soooo what should i use then?
Your mind! OK seriously, look at all the ways you can use replace. It is actually the easiest one to do.

You can use string.length() and replace to do it. Just like what you did with other ones above. Here is the code which works
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
26
27
28
29
30
31
32
33
34
35
36
  #include <iostream>
#include <string>

using namespace std;

int main()
{
	string information;

	int name, ssn, userID, password;

	cout << "Enter a student's name, social security number(include dashes), user id, and password in one line:" << endl;
	getline(cin, information);
	cout << endl;

	name = information.find(' ', 0);
	cout <<"name is " <<name <<endl;

	ssn = information.find(' ', name + 1);
	cout << "ssn is " <<ssn<<endl;
	information.replace(name + 1, 3, "xxx");
	information.replace(name + 5, 2, "xx");
	information.replace(name + 8, 4, "xxxx");

	userID = information.find(' ', ssn + 1);
    cout << "userID is " <<userID<<endl;
	
    for(unsigned int i=userID+1; i <information.length(); i++){
     information.replace(i,1,"x");    
    }
    
	cout << information << endl;
	cin.clear();
        getchar();
	return 0;
}


Please restrain from using system("pause"). It is a bad programming practice since it runs your OS command line "pause" program. Hope this helps
Topic archived. No new replies allowed.