c++ - 无法在 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 中不起作用
解决方案
改变
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 tellg
is not an int
,通过使用auto
您要求编译器使用正确的类型,无论是什么类型。
推荐阅读
- python - 通过 Xpath 查找无法按预期工作?硒蟒
- angular8 - 如何退订 BehaviorSubject Angular 8
- docker - 为什么我的 Haskell 程序不能在带有 Alpine 或 Scratch 的 Docker 中运行?
- excel - 使用 VBA 单击 javascript 链接,出现“需要对象”错误
- java - gson 对象往返 json 导致异常
- php - 在 MAMP Pro 中安装 PHP ZIP 扩展
- python - 更改列表中特定元素的类型 - python
- google-apps-script - 从 gmail 正文中提取行+列到电子表格
- c++ - 为什么 QProcess::readAllStandardOutput 读取不是所有的输出通道?
- python - 从递归嵌套的字段列表创建部分字典