identifier "string" undefined?

C++String

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

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.

Solution 3 - C++

You forgot the namespace you're referring to. Add

using namespace std;

to avoid std::string all the time.

Solution 4 - C++

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

Solution 5 - C++

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

Solution 6 - C++

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;

Solution 7 - C++

#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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRhexisView Question on Stackoverflow
Solution 1 - C++PuppyView Answer on Stackoverflow
Solution 2 - C++FlexoView Answer on Stackoverflow
Solution 3 - C++m0skit0View Answer on Stackoverflow
Solution 4 - C++Ernest Friedman-HillView Answer on Stackoverflow
Solution 5 - C++Nicol BolasView Answer on Stackoverflow
Solution 6 - C++CamelotView Answer on Stackoverflow
Solution 7 - C++Pierre LacaveView Answer on Stackoverflow