I was learning C++ from the C++ primer book(5E) and the exercise 3.6 says,
“Use a range for to change all the characters in a string to X.” .
I instead tried to take a little bit further by changing all but the last 4 characters to X like for a credit card detail.
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
cout << "Enter you credit card number: ";
string ccno;
cin >> ccno;
for (decltype(ccno.size()) c = 0; c < ccno.size() - 4; ++c)
ccno[c] = 'X';
cout << ccno << endl;
return 0;
}
It gave the desired result.
Then I moved onto the next exercise (3.7) which says,
“What would happen if you define the loop control variable in the previous exercise as type char? Predict the results and then change your program to use a char to see if you were right.” .
I went ahead and just changed the initial type to char type:
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
cout << "Enter you credit card number: ";
string ccno;
cin >> ccno;
for (char c = 0; c < ccno.size() - 4; ++c)
ccno[c] = 'X';
cout << ccno << endl;
return 0;
Unexpectedly, it didn’t raise any error message and again gave the same(desired) output as before.
e.g.
input: whatever
output: XXXXever
So I decided to check the unofficial answers for these exercises and found these:
For 3.6:
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main()
{
string str = "gaoxiangnumber1";
for(char &ch : str)
{
ch = 'X';
}
cout << str;
return 0;
}
/*
Output:
XXXXXXXXXXXXXXX
*/
For 3.7:
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main()
{
string str = "gaoxiangnumber1";
for(char ch : str)
{
ch = 'X';
}
cout << str;
return 0;
}
/*
Output:
gaoxiangnumber1
*/
Surprisingly, their outputs are different. For the 3.7, it doesn’t change the given string at all.
I tried to find similar questions on StackOverflow but I couldn’t find any related ones. Even if I did, I was too novice to realize that they were similar questions and could not understand those.
Is it because I’m comparing ‘c’ to a size_t datatype in my for loop that it’s somehow changing c’s type in the backhand or something? Or is it because I’m taking inputs unlike the unofficial answers which are initializing it beforehand(That sounds like the most foolish reason but yeah)