不能 运行 在 visual studio 中用指针和 fstream 编程

cannot run program with pointer and fstream in visual studio

我可以在 codeblock 或 visual studio 2015 中 运行 我的程序,但它在 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 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    

我可以在 codeblock 或 visual studio 2015 中 运行 我的程序,但它在 visual studio 2017

中不起作用

您不能将 const char*(在您的情况下是字符串文字 "caua.txt" 传递给接受非常量 char* 的函数。

将您的签名更改为 void replacechar(const char *filenguon, char ktc, char ktm)

改变

void replacechar(char *filenguon, char ktc, char ktm)

void replacechar(const char *filenguon, char ktc, char ktm)

有关 字符串文字的规则 在 C++11 中发生了变化(我认为)。它们是常量数据,因此您传递字符串文字的任何函数参数都应使用 const.

声明

并且,如评论中所述,更改

int pos = fs.tellg();

auto pos = fs.tellg();

来自 tellg 的 return 不是 int,通过使用 auto,您要求编译器使用正确的类型,无论是什么类型。

两种方法:
1.

void replacechar(const char *filenguon, char ktc, char ktm)
{
    //TODO
}
    2.
char str[]={"caua.txt";};
replacechar(str, 'r', 'R');

应该可以,"caua.txt"是const char*,逐个复制变成char*或者const_cast<char*>