Why can't I declare a string in my program: “string is undeclared identifier”

Deadly 提交于 2020-04-06 03:15:30

问题


I can't declare a string in my program:

string MessageBoxText = CharNameTextBox->Text;

it just doesn't work. It says string is undeclared identifier. What am I missing in the namespace or include or something like that?


回答1:


Make sure you've included this header:

#include <string>

And then use std::string instead of string. It is because string is defined in std namespace.

And don't write this at namespace scope:

using namespace std; //bad practice if you write this at namespace scope

However, writing it at function scope is not that bad. But the best is one which I suggested before:

Use std::string as:

std::string MessageBoxText = CharNameTextBox->Text;



回答2:


To use the standard string class in C++ you need to #include <string>. Once you've added the #include directive string will be defined in the std namespace and you can refer to it as std::string.

E.g.

#include <string>
#include <iostream>

int main()
{
    std::string hw( "Hello, world!\n" );
    std::cout << hw;
    return 0;
}



回答3:


Are you by any way compiling using C++/CLI, the Microsoft extension for .NET, and not standard ISO C++?

In that case you should do the following:

System::String^ MessageBoxText = CharNameTextBox->Text;

Also see the following articles:

  • How to: Convert Between Various String Types
  • How to: Convert System::String to Standard String
  • How to: Convert Standard String to System::String


来源:https://stackoverflow.com/questions/7625105/why-cant-i-declare-a-string-in-my-program-string-is-undeclared-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!