无法在visual studio中使用指针和fstream运行程序

问题描述 投票:-1回答:3

我可以在codeblock或visual studio 2015中运行我的程序,但它在2017年的Visual Studio中不起作用

#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中运行我的程序,但它在2017年的Visual Studio中不起作用

c++ visual-studio-2017 fstream
3个回答
2
投票

你不能传递const char*(在你的情况下,字符串文字"caua.txt"到一个接受非const char*的函数。

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


3
投票

更改

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();

tellg的回归不是int,通过使用auto,你要求编译器使用正确的类型,无论是什么。


2
投票

两种方法: 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*>

© www.soinside.com 2019 - 2024. All rights reserved.