0
votes

I have a template class Polinom, that uses generic data types(int, float, double, class Complex(defined by me)), and I want to convert a string to Polinom using this function for reading and a constructor:

Polion.cpp

 template<typename T>
 istream& operator>>(istream& in, Polinom<T>& P) {
     char line[1000];
     in.getline(line, 1000);
     int gr = -1;
     T cf[100];
     char* pt;
     pt = strtok(linie, " ");
     while (pt) {
        cf[++gr] = T(pt);
        pt = strtok(NULL, " ");
     }
     P = Polinom<T>(gr, cf);
     return in;
 }

Complex.cpp

  Complex::Complex(const char* str){
    /*
    ...
    */
    }

Everything is fine when I use Complex data type ( Polinom a(12, 4); std::cout << a << endl;) // I defined a friend ostream function for this line; ) because I write this constructor Complex::Complex(const char* str)

The problems appears when I use primitive data types

   Polinom<int> a(12, 4); because of T(const char* ) ===> int(const char*)

How can I solve this? Thank you very much!

2
Do you want your tokens to ONLY split on space ' '? Or is any whitespace appropriate for token splitting (en.cppreference.com/w/cpp/string/byte/isspace) - JohnFilleau
I want my tokens to split only on space ' '. Thank you! - Andrei Alexandru Dughila

2 Answers

0
votes

This looks like you're reinventing the wheel. There's already a proper operator>> for int. You should add an overload for your Complex, so that in >> cf[gr++] compiles for every T.

0
votes

I updated my code like this:

Polinom.cpp

 template<typename T>
 istream& operator>>(istream& in, Polinom<T>& P) {
     char linie[1000];
     in.getline(linie, 1000);
     int gr = -1;
     T cf[100];
     char* pt;
     pt = strtok(linie, " ");
     while (pt) {
       T a;
       string aux;
       try {
          aux = string(pt);
          if(aux.find("i") != string::npos) throw std::invalid_argument("invalid");
          a = std::stod(pt);
       }
       catch(const std::invalid_argument& e){
           cf[++gr] = (T)(pt);
           goto execute;
       }
      cf[++gr] = a;
      execute:
      pt = strtok(NULL, " ");
      }
      P = Polinom<T>(gr, cf);
      return in;
  }
 int main()
 {
    Polinom<Complex> a(12, 4);   // it works
    std::cout << a << endl; 
    Polinom<int> b;             // it works
    std::cin >> b;
    std::cout << b;
    Polinom<double> c;         // error C2440   'type cast': cannot convert from char* 
                               // to 'T'
    std::cin >> c;
    std::cout << c;
    return 0;

}