-1

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;
    }
};
AskMath
  • 415
  • 1
  • 4
  • 11
  • Resolving `str()` works fine in https://godbolt.org/g/8KKrgh (after fixing the mistyped class name), but `std::fputs` expects a `char*`, not a `string`. – Christopher Creutzig Jun 04 '18 at 07:10
  • @ChristopherCreutzig And how can I fix it? – AskMath Jun 04 '18 at 07:11
  • Possible duplicate of [How to write user input to a text file using fputs in C++](https://stackoverflow.com/questions/5546725/how-to-write-user-input-to-a-text-file-using-fputs-in-c) –  Jun 04 '18 at 07:18
  • @NickyC I tried it : `if (std::fputs(ss.str().c_str(), this->file) == EOF)` and it's not working yet.. – AskMath Jun 04 '18 at 07:21
  • What is the error after you change to `if (std::fputs(ss.str().c_str(), this->file) == EOF)`? – zhm Jun 04 '18 at 07:23
  • @MartinZhai I edited my question - see now. – AskMath Jun 04 '18 at 07:24
  • What compiler are you using? I test with visual studio and MingGW, both work after change to `if (std::fputs(ss.str().c_str(), this->file) == EOF)`. – zhm Jun 04 '18 at 07:25
  • @MartinZhai with eclipse – AskMath Jun 04 '18 at 07:26

2 Answers2

3

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).

sebrockm
  • 5,733
  • 2
  • 16
  • 39
  • Your updated code compiles just fine with gcc. Every standard-compliant compiler should be able to compile it... – sebrockm Jun 04 '18 at 07:52
0
    std::ostringstream oss;
    FILE *file;
    std::string s = oss.str();
    std::cout << s << '\n';
    std::fputs(s.c_str(), file);

covert ostringstream to std::string and than convert in const char *