I am very confused about when to use string (char) and when to use string pointers (char pointers) in C++. Here are two questions I’m having.
which one of the following two is correct?
string subString;
subString = anotherString.sub(9);
string *subString;
subString = &anotherString.sub(9);
which one of the following two is correct?
char doubleQuote = aString[9];
if (doubleQuote == "\"") {...}
char *doubleQuote = &aString[9];
if (doubleQuote == "\"") {...}
None of them are correct.
The member function
subdoes not exist for string, unless you are using anotherstringclass that is notstd::string.The second one of the first question
subString = &anotherString.sub(9);is not safe, as you’re storing the address of a temporary. It is also wrong asanotherStringis a pointer to a string object. To call thesubmember function, you need to writeanotherString->sub(9). And again, member functionsubdoes not exist.The first one of the second question is more correct than the second one; all you need to do is replace
"\""with'\"'.The second one of the second question is wrong, as:
doubleQuotedoes not refer to the 10th character, but the string from the 10th character onwardsdoubleQuote == "\""may be type-wise correct, but it doesn’t compare equality of the two strings; it checks if they are pointing to the same thing. If you want to check the equality of the two strings, use strcmp.