Been coding C++ for about a week now haha, and have run in to a problem. I am working through a book and one of the exercises calls for reading a string that has punctuation marks in it and then printing the string, but without those punctuation marks.
Now, on using the string "Hello World!!!" (yes, indeed) and the following code I can succeed in printing "Hello World" which is great:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <string>
using std::string; using std::cout; using std::cin; using std::endl;
int main ()
{
string s ("Hello World!!!");
for (decltype(s.size()) index = 0;
index != s.size() && !ispunct(s[index]); ++index)
cout << s[index];
return 0;
}
However, I got to thinking, what happens if one has a string that looks like "Hello, World!!!", or "Thi.s str&in$g is mess$ed up" how would I adapt the above code in order to return "Hello World" or "This string is messed up"?
Fantastic!! Really simple solution (as expected). It is taking me a little longer than expected to wrap my head around some of the code but with help like this I should get it soon.
I'd like to ask another question if I may. It is from the same exercise in the book and based on the Range-Based for: "Use range for to change all the characters in a string to X."
I coded the following which works, but I know is not correct:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <string>
using std::string; using std::cout; using std::cin; using std::endl;
int main ()
{
string s ("Hello World!");
for (auto &c : s)
cout << "X";
return 0;
}
It obviously changes everything to X, but it doesn't use the &c reference and just doesn't look correct.
Vlad, thanks a million! I think I can see where my problem was. I had tried to put the c = "X" not c = 'X', I got some error about incompatible types (one is string other is char).
This works perfectly. Can you explain why in single quotes it works but not with double quotes?