views:

399

answers:

4

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 == "\"") {...}
+3  A: 

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:

  1. doubleQuote does not refer to the 10th character, but the string from the 10th character onwards
  2. doubleQuote == "\"" 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.
blwy10
A: 

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 == '\"') { ... }
Cătălin Pitiș
A: 

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.

Ashalynd
`std::string` doesn't belong to that part of the std lib that came from the STL.
sbi
Oh, and `mystring[9]` works, too. It's just that `std::string::at()` checks its argument, while `std::string::operator[]()` doesn't. It depends on which you need.
sbi
+2  A: 

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.

sbi