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

2019-08-27 15:54发布

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.

4条回答
戒情不戒烟
2楼-- · 2019-08-27 16:18

"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.

查看更多
做个烂人
3楼-- · 2019-08-27 16:29

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

查看更多
手持菜刀,她持情操
4楼-- · 2019-08-27 16:32

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.

查看更多
成全新的幸福
5楼-- · 2019-08-27 16:41

Do you just mean:

std::string x = "Slim Shady";
查看更多
登录 后发表回答