What is the data type for a string? [closed]

2019-08-27 15:49发布

问题:

This is most likely a very stupid question, but in C++, what is the data type for a string? I want to make the variable x = "Slim Shady".

Would I declare x as an int? I have tried declaring it as a char, but when I cout the variable, it only gives the first letter. Any help would be appreciated.

回答1:

You need to include the header file string

#include <string>

Then you will be able to use std::string

std::string x="Slim Shady"

http://en.cppreference.com/w/cpp/string/basic_string

You can also not use std::strings, if you dont want to use them althought they are your best option

You can use Char arrays or char pointer (C-strings)

char x[]="Slim Shady";

or

char* x="Slim Shady";

The auto keyword is a C++0x feature. You should stay away from it till you learn the C++ basics



回答2:

std::string is the best bet. But you can also use auto, as in auto x = "Slim Shady!";. This means that you don't have to figure out the type to use the expression.



回答3:

"Slim Shady" is constant literal of type char[11] which is convertible to const char*. You can also use it for initialization of any char arrays bigger than 11. See:

char a[] = "Slim Shady";
char a[11] = "Slim Shady";
const char* a = "Slim Shady";
char a[12] = "Slim Shady";

See this little code:

#include <typeinfo>
#include <iostream>

template <class T>
void printTypeName(T t)
{
   std::cout << typeid(T).name() << std::endl;
}

int main() {
  printTypeName("Slim Shady");
  printTypeName<decltype("Slim Shady")>("Slim Shady");
}

You get (on gcc) mangled names:

PKc
A11_c 

From what I know - the first is const char* the second is char[11]. This is easy to explain since when passing array of anything to function - it is converted to const pointer.



回答4:

Do you just mean:

std::string x = "Slim Shady";