Reputation: 13311
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 == "\"") {...}
Upvotes: 0
Views: 10574
Reputation: 224049
In C++, you can (and should) always use std::string
(while remembering that string literals actually are zero-terminated character arrays). Use char*
only when you need to interface with C code.
C-style strings need error-prone manual memory management, need to explicitly copy strings (copying pointers doesn't copy the string), and you need to pay attention to details like allocating enough memory to have the terminating '\0'
fit in, while std::string
takes care of all this automagically.
Upvotes: 3
Reputation: 12563
Erm, are you using string from STL?
(i.e. you have something like
#include <string>
#using namespace std;
in the beginning of your source file ;) )
then it would be like
string mystring("whatever:\"\""");
char anElem = mystring[9];
if (anElem=="\"") { do_something();}
or you can write
mystring.at(9)
instead of square brackets.
May be these examples can help.
Upvotes: 0
Reputation: 14341
For the first question, the first sample, assuming sub will return a substring of the provided string.
For the second, none:
char doubleQuote = aString[9];
if( doubleQuote == '\"') { ... }
Upvotes: 0
Reputation: 4892
None of them are correct.
The member function sub
does not exist for string, unless you are using another string
class that is not std::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 as anotherString
is a pointer to a string object. To call the sub
member function, you need to write anotherString->sub(9)
. And again, member function sub
does 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:
doubleQuote
does 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.Upvotes: 4