Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is "my text" a std::string, a *char or a c-string?

Tags:

c++

string

char

I have just done what appears to be a common newbie mistake:

First we read one of many tutorials that goes like this:

 #include <fstream>
 int main() {
      using namespace std;
      ifstream inf("file.txt");
      // (...)
 }  

Secondly, we try to use something similar in our code, which goes something like this:

#include <fstream>
int main() {
    using namespace std;
    std::string file = "file.txt"; // Or get the name of the file 
                                   // from a function that returns std::string.
    ifstream inf(file);
    // (...)
}

Thirdly, the newbie developer is perplexed by some cryptic compiler error message.

The problem is that ifstream takes const * char as a constructor argument.

The solution is to convert std::string to const * char.

Now, the real problem is that, for a newbie, "file.txt" or similar examples given in almost all the tutorials very much looks like a std::string.

So, is "my text" a std::string, a c-string or a *char, or does it depend on the context?

Can you provide examples on how "my text" would be interpreted differently according to context?

[Edit: I thought the example above would have made it obvious, but I should have been more explicit nonetheless: what I mean is the type of any string enclosed within double quotes, i.e. "myfilename.txt", not the meaning of the word 'string'.]

Thanks.

like image 404
augustin Avatar asked Aug 21 '10 01:08

augustin


1 Answers

So, is "string" a std::string, a c-string or a *char, or does it depend on the context?

  • Neither C nor C++ have a built-in string data type, so any double-quoted strings in your code are essentially const char * (or const char [] to be exact). "C string" usually refers to this, specifically a character array with a null terminator.
  • In C++, std::string is a convenience class that wraps a raw string into an object. By using this, you can avoid having to do (messy) pointer arithmetic and memory reallocations by yourself.
  • Most standard library functions still take only char * (or const char *) parameters.
  • You can implicitly convert a char * into std::string because the latter has a constructor to do that.
  • You must explicitly convert a std::string into a const char * by using the c_str() method.

Thanks to Clark Gaebel for pointing out constness, and jalf and GMan for mentioning that it is actually an array.

like image 153
casablanca Avatar answered Sep 23 '22 11:09

casablanca