0

I am having trouble using string variables inside of a class in c++. I have tried using include but that doesn't appear to have any noticeable effect. Here are the contents of the header file the class is declared in:

#include <string.h>

#ifndef STUDENT_H
#define STUDENT_H

class Student
{
private:
    int iStudentAge;
    int iStudentBirthDay;
    int iStudentBirthMonth;
    int iStudentBirthYear;
    string sStudentName;
    string sStudentCourse;
public:
    Student();
    Student(int iValue1, int iValue2, int iValue3, int iValue4, string sValue5, string sValue6);
    void setAge(int iNewValue);
    int getAge();
    void setBirthDay(int iNewValue);
    int getBirthDay();
    void setBirthMonth(int iNewValue);
    int getBirthMonth();
    void setBirthYear(int iNewValue);
    int getBirthYear();
    void setName(string iNewValue);
    string getName();
    void setCourse(string iNewValue);
    string getCourse();
};

#endif // !STUDENT_H

The specific errors I am having are all on the lines that involve strings, except for the include line.

Micah Lehman
  • 81
  • 1
  • 1
  • 8

3 Answers3

6

<string.h> is the C header file for string handling null-terminated byte strings. std::string is defined in the header file <string>.

So first change your include to the correct file, then you need to use the std:: scope prefix for all strings.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

For C++ you should use the according library #include <string> not #include <string.h> witch is a C library.

For variable declaration use scope

std::string sStudentName;

or

using namespace std;

before the class declaration for string to be recognized as a type.

The first option is recommended, to know why see Why is “using namespace std;” considered bad practice?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • Please do not suggest to use `using namespace std;` in a header file: https://stackoverflow.com/q/1452721/3684343 – mch Jan 28 '20 at 11:48
  • 1
    @mch, I did recommend the first option, if it exists and can be used, it's best to talk about it and say why it shouldn't be, I added the link to my answer. – anastaciu Jan 28 '20 at 12:04
1

As a compromise between littering "std::" all over the file, and using the potentially dangerous "using namespace std", you can write:

using std::string;
AlexGeorg
  • 967
  • 1
  • 7
  • 16