80

I am receiving the error: identifier "string" undefined.

However, I am including string.h and in my main file, everything is working fine.

CODE:

#pragma once
#include <iostream>
#include <time.h>
#include <string.h>

class difficulty
{
private:
    int lives;
    string level;
public:
    difficulty(void);
    ~difficulty(void);

    void setLives(int newLives);
    int getLives();

    void setLevel(string newLevel);
    string getLevel();
};

Can someone please explain to me why this is occurring?

1
  • 3
    As a side comment, you should use include guards in your code. If your compiler does better with the #pragma once directive, combine the two: #ifndef XXX_HEADER // #define XXX_HEADER // #pragma once // ... // #endif where the order is important (i.e. include guard enclosing the pragma) Aug 22, 2011 at 12:00

7 Answers 7

124

<string.h> is the old C header. C++ provides <string>, and then it should be referred to as std::string.

1
  • 17
    Don't using namespace std, I've already downvoted all the answers that recommend that for a reason.
    – Puppy
    Mar 29, 2016 at 13:35
27

You want to do #include <string> instead of string.h and then the type string lives in the std namespace, so you will need to use std::string to refer to it.

13

You forgot the namespace you're referring to. Add

using namespace std;

to avoid std::string all the time.

5
  • 8
    For those who downvoted: thanks for your constructive comments :P
    – m0skit0
    Aug 22, 2011 at 11:27
  • 4
    using namespace std; is really bad, especially in a header.
    – Puppy
    Aug 22, 2011 at 13:13
  • 2
    Thanks! Can you please explain why?
    – m0skit0
    Aug 22, 2011 at 16:17
  • There's an SO question about it, I believe.
    – Puppy
    Aug 22, 2011 at 20:03
  • 7
    Here (if someone wants to know)
    – m0skit0
    May 22, 2012 at 19:49
11

Because string is defined in the namespace std. Replace string with std::string, or add

using std::string;

below your include lines.

It probably works in main.cpp because some other header has this using line in it (or something similar).

6

#include <string> would be the correct c++ include, also you need to specify the namespace with std::string or more generally with using namespace std;

5

Perhaps you wanted to #include<string>, not <string.h>. std::string also needs a namespace qualification, or an explicit using directive.

5

You must use std namespace. If this code in main.cpp you should write

using namespace std;

If this declaration is in header, then you shouldn't include namespace and just write

std::string level;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.