无法在Visual Studio中使用指针和fstream运行程序

时间:2019-03-29 09:19:59

标签: c++ visual-studio-2017 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中不起作用

3 个答案:

答案 0 :(得分: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,您是在要求编译器使用正确的类型,无论是什么类型。

答案 1 :(得分:2)

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

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

答案 2 :(得分: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*>