2 minute read


The string data type is a very useful data type that we often use to store text in our C++ programs. However, we can often get errors from the compiler such as:

error: identifier “string” is undefined

This error is pretty straight-forward to fix as we will see below.

Fix #1: Add string to your depedencies

Essentially, the string data type must have access to the string library in order to be executed by the compiler.

Therefore, you must add the following #include header to the top of your code (in the include(s) part) such as:

#include <string> //Add this
#include <iostream>

int main() {
    std::string x = "Hello!";
    std::cout << x << std::endl; //Returns "Hello!"

    return 0;

The compiler should now recognize the string data type, thus fixing the identifier string is undefined error.

If the std error still persists, keep reading below.

Fix #2: Using namespace std

Note that we have previously typed: std::string instead of string. We can type “string” only if we are declaring that we are using its namespace.

In other words, we would need to type “using namespace std” in the header if we only want to type string (which is obviously shorter) instead of std::string. For instance, we can have something like:

#include <string>
#include <iostream>
using namespace std;

int main() {
    string x = "Hello!";
    cout << x << endl; //Returns "Hello!"

    return 0;

It is okay to type std::string without typing “using namespace std”. In fact, it is generally recommended to type the full std::string name (and therefore avoiding using namespace std) when working with multiple libraries because it can reduce future confusion.

However, if you still want to type “string” instead of “std::string”, then you need to add “using namespace std” to the header


Read more about the std::string library here: https://en.cppreference.com/w/cpp/string/basic_string