Home > Enterprise >  Adding functions to string class in c
Adding functions to string class in c

Time:11-16

I am using the up to date compiler for gcc. Therefore my code can execute to_String() and stoi() but unfortunately the platform that I am trying to compile my code in has a much previous one and I want to add these two functions into the string class therefore I can use them in my code without any problem.This is one of each example of the errors I get.

Cabinet.cpp:93:25: error: 'to_string' was not declared in this scope
 cout << to_string(id) << " not found"<<endl;
LabOrganizer.cpp: In member function 'void LabOrganizer::findClosest(int, int, int)':
LabOrganizer.cpp:294:38: error: 'stoi' was not declared in this scope
        cc = stoi(arr1[i].substr(1,1))-1;

CodePudding user response:

These two functions aren't part of the "string class". All you need is to use alternatives that existed in 1998:

  • The to_string function isn't even needed in this context. You can simply change it to:

    cout << id << " not found" << endl;
    
  • You can replace stoi with atoi. It doesn't throw exceptions if the conversion fails, but since it's a school assignment -- you most probably don't care about that:

    cc = atoi(arr1[i].substr(1,1).c_str())-1;
    

If you have many instances whose replacement is too cumbersome, you can, of course, define those functions in some common header file:

template<class T>
std::string to_string(const T &x) {
    std::ostringstream s;
    s << x;
    return s.str();
}

inline int stoi(const std::string &s) {
    // ... ignores error handling ...
    return atoi(s.c_str());
}

Hopefully this compiles with that 1998 GCC.

  • Related