c++ - 如何修复“未知类型名称'变量'”?
问题描述
我在网上找了一些代码来写一个二进制文件,但是当我想执行它时,编译器给我一个错误
未知类型名称“fs”
我怎样才能解决这个问题?
#include <fstream>
namespace std{
string token = "token";
std::ofstream fs("example.bin", ios::out | ios::binary | ios::app);
fs.write(token, sizeof token);
fs.close();
}
解决方案
块内不能有非声明语句namespace
。使用std::string
andstd::ofstream
对象的代码需要在函数内部,如果需要,可以在 a 内部声明namespace
。std
此外,无论如何,向命名空间添加新内容是非法的。
此外,您不能以代码尝试的方式创建对象write()
。std::string
它不仅不会编译开始(第一个参数需要一个char*
指针),而且无论如何它在逻辑上都是错误的,因为 astd::string
将其字符数据存储在内存中的其他位置,因此您将写入该std::string
数据的内部指针,而不是实际数据本身。
试试这个:
#include <fstream>
#include <string>
namespace my_ns{
void save() {
std::string token = "token";
std::ofstream fs("example.bin", std::ios::binary | std::ios::app);
fs.write(token.c_str(), token.size());
fs.close();
}
}
int main() {
my_ns::save();
return 0;
}
不过,我怀疑原始代码实际上是在尝试做更多类似的事情:
#include <fstream>
#include <string>
using namespace std; // <--
int main() {
string token = "token";
ofstream fs("example.bin", ios::binary | ios::app);
fs.write(token.c_str(), token.size());
fs.close();
return 0;
}
推荐阅读
- kotlin - 抽象类可以在 Kotlin 中包含非抽象类参数吗?
- tcp - 这个 TCP 拥塞控制图中发生了什么?
- php - 将foreach循环的值保存在php中的本地初始化数组中
- python - 使用 Tkinter 功能创建多个下拉菜单并允许用户选择和显示不同的选项
- node.js - 使用预签名 URL 流式上传到 S3
- parsing - 解析飞镖 | ANTLR | 处理参数列表末尾的逗号
- haskell - 为什么 Haskell 的列表没有作为 State Monad 的一个实例?
- glm - 如何将 R 中的伽马 GLM 与响应变量的右删失观测值拟合?
- flutter - ModalBottomSheet Flutter 中的组复选框
- discord.js - 我的机器人的 Discord javascript 问题无法读取属性