Search code examples
c++visual-studio-2017fstream

cannot run program with pointer and fstream in visual studio


I can run my program in codeblock or visual studio 2015 but it doesn't work in visual studio 2017

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
void replacechar(char *filenguon, char ktc, char ktm)
{
    fstream fs(filenguon, ios::in | ios::out);
    if (!fs)
        cout << "khong the tim thay" << endl;
    else
    {
        char ch;
        while (fs.get(ch))
        {
            if (ch == ktc)
            {
                int pos = fs.tellg();
                pos--;
                fs.seekp(pos);
                fs.put(ktm);
                fs.seekg(pos + 1);
            }
        }
    }
}

int main()
{
    replacechar("caua.txt", 'r', 'R');
    return 0;
}

Error:

  Error C2664   'void replacechar(char *,char,char)': cannot convert argument 1 from 'const char [9]' to 'char *'   

    Error (active)  E0167   argument of type "const char *" is incompatible with parameter of type "char *" 

    Warning C4244   'initializing': conversion from 'std::streamoff' to 'int', possible loss of data    

I can run my program in codeblock or visual studio 2015 but it doesn't work in visual studio 2017


Solution

  • You are not allowed to pass a const char* (in your case the string literal "caua.txt" to a function accepting a non-const char*.

    Change your signature to void replacechar(const char *filenguon, char ktc, char ktm).