Search code examples
c++c++11operator-overloadingostringstream

How can I fix this error? "Method 'str' could not be resolved"


What is the meaning of this problem and how can I fix it?
It's look like it's not meet the function str() while I try to use it.
In fact, I want to take the "string" from rhs and to put it in this->file, so if you have alternative idea, it's good too.

Method 'str' could not be resolved
Method 'c_str' could not be resolved

#include <cstdio>
#include <iostream>
#include <sstream>

class MyFile {
    FILE* file;
    MyFile& operator=(const MyFile& rhs) const;
    MyFile(const MyFile& rhs);
public:
    MyFile(const char* filename) :
            file(fopen(filename, "w")) {
        if (file == NULL) {
            throw std::exception();
        }
    }
    ~MyFile() {
        fclose(file);
    }

    template<typename T>
    MyFile& operator<<(const T& rhs) {
        std::ostringstream ss;
        ss << rhs;
        if (std::fputs(ss.str().c_str(), this->file) == EOF) { // Method 'str' could not be resolved
            throw std::exception();
        }
        return *this;
    }
};

Solution

  • Are you sure that str() is the function that cannot be resolved? Instead, I assume fputs() cannot be resolved. The reason is that fputs expects a const char*, but you are giving it an std::string which is returned by str(). Try fputs(ss.str().c_str(), this->file).