Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ g++ can't find 'string' type in class header file

I'm new to C++ but I can't figure out why this won't compile for me. I'm running on a Mac, coding with Xcode, but I'm building with my own makefile from bash.

Anyway, I'm getting two compiler errors that "string" type can't be found, even though I've included . Any help would be welcomed. Code:

//#include <string> // I've tried it here, too. I'm foggy on include semantics, but I think it should be safe inside the current preprocessor "branch"
#ifndef APPCONTROLLER_H
#define APPCONTROLLER_H

#include <string>
class AppController {
// etc.
public:
    int processInputEvents(string input); //error: ‘string’ has not been declared
    string prompt(); //error: ‘string’ does not name a type
};
#endif

I include this file in my main.cpp, and elsewhere in main I use the string type and it works just fine. Though in main I have included iostream instead of string (for other purposes). Yes, I've also tried including iostream in my AppController class but it didn't solve anything (I didn't really expect it to, either).

So I'm not really sure what the problem is. Any ideas?

like image 993
jbrennan Avatar asked Feb 04 '11 02:02

jbrennan


People also ask

What is the header file for the string class in C?

cstring is the header file required for string functions. This function Returns a pointer to the last occurrence of a character in a string.

What is the header file for the string class?

What is the header file for the string class? Explanation: #include<string> is the header file for the string class.

Is string is a header file?

h is the header in the C standard library for the C programming language which contains macro definitions, constants and declarations of functions and types used not only for string handling but also various memory handling functions; the name is thus something of a misnomer.

How do I import a string in C++?

In order to use the string data type, the C++ string header <string> must be included at the top of the program. Also, you'll need to include using namespace std; to make the short name string visible instead of requiring the cumbersome std::string.


1 Answers

string is in the std namespace.

#include <string>
...
std::string myString;

Alternatively you can use

using namespace std;

However, this is a very bad thing to do in headers as it will pollute the global namespace for anyone that includes said header. It's ok for source files though. There is an additional syntax you can use (that has some of the same problems as using namespace does):

using std::string;

This will also bring the string type name into the global namespace (or the current namespace), and as such should generally be avoided in headers.

like image 56
Washu Avatar answered Oct 04 '22 12:10

Washu