-2

i have this code using class. how function getDept() can return first 3 char of string?

if i input a1234567 i need function getDept() return a12

class ID
{
    string value;
    public:
        ID() { value=""; }
        void setID(string p) { value=p; }
        string getID(){return value;}
        string getDept() { ... }           //get first 3 char of string
};

int main()
{
    ID *emp = new ID;
    char st[10];
    for(int i=0; i<3; i++){
        emp->setID(st);
        cout << emp->getID() << "have departement code : " << 
        emp->getDept() << " " << endl;
    }
    return 0;
}
Newb
  • 19
  • 4
  • `char st[10]; emp->setID(st);` is bad because `st` is not initialized. – MikeCAT Apr 26 '21 at 11:59
  • Tip: Avoid `new`. Avoid C strings, use `std::string`. **Always initialize values before using them**. – tadman Apr 26 '21 at 12:00
  • Tip: For a getter, use a pattern like`const std::string& getX() { return x; } const`, with `const` references returned, and `const` set on the member function. – tadman Apr 26 '21 at 12:01

2 Answers2

3

If string here means std::string, you can use the substr() function.

string getDept() {
    return value.substr(0, 3);
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

add using namespace std; to your project then just

string getdept()
{
    return value.substr(0, 3);
}
Ali
  • 376
  • 5
  • 16
  • 2
    [c++ - Why is "using namespace std;" considered bad practice? - Stack Overflow](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – MikeCAT Apr 26 '21 at 12:08