首页 > 解决方案 > 无法在 Visual Studio 中使用指针和 fstream 运行程序

问题描述

我可以在代码块或 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    

我可以在代码块或 Visual Studio 2015 中运行我的程序,但它在 Visual Studio 2017 中不起作用

标签: c++visual-studio-2017fstream

解决方案


改变

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

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

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

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

int pos = fs.tellg();

auto pos = fs.tellg();

返回 from tellgis not an int,通过使用auto您要求编译器使用正确的类型,无论是什么类型。


推荐阅读