There are a couple of ways to do this. One of them involves reading the input right off of the input stream, and another involves dumping the whole input into a string and picking out the parts that you want.
Since the name is followed immediately by the SSN, one thing you could do is grab input and stick it onto the name until you run into a digit.
Then do what I mentioned above.
For instance, something like this:
cout << "Enter your name followed by a something starting with a number:";
cout << "\n>> ";
while (!isdigit(cin.peek())) // Peek at the next character in the input
cin >> tmp;
cin.ignore(); // Get rid of the whitespace
name += (tmp + ' ');
name.pop_back(); // Get rid of the trailing space, not like it matters
// If you have an older compiler, you might need to replace that line with
cin >> other;
cout << "Your name is " << name;
cout << "\nand the other thing you entered was " << other;
This produces the output:
Enter your name followed by a something starting with a number:
>> Jay Jay the Jet Plane 123that's-me!
Your name is Jay Jay the Jet Plane
and the other thing you entered was 123that's-me!
If you decide to use getline
to grab the whole input all at once, you can use std::find_if
) to find where the first digit (presumably the start of the SSN) is, and then use the substr
member function of std::string
to grab everything up to that point (which will presumably be the full name).
As for "actually" replacing the digits of the SSN, you can use std::replace_if
) to replace all of the digits with 'x's.
(Or you can just do what you've already been doing, since you know that the SSN has to be in that format)
(For those of you who can tell, I'm just trying to dodge the use of
Or...since you can't use
to access string elements, you can just use iterators for everything instead:
(Geez, why didn't I think of that before?)
for (std::string::iterator it = ssn.begin(); it != ssn.end(); ++it)
if (std::isdigit(*it)) // or if (*it != '-')
*it = 'x'; // Replace digits with 'x'