首页 > 解决方案 > 如何修复“未知类型名称'变量'”?

问题描述

我在网上找了一些代码来写一个二进制文件,但是当我想执行它时,编译器给我一个错误

未知类型名称“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();
}

标签: c++binaryfiles

解决方案


块内不能有非声明语句namespace。使用std::stringandstd::ofstream对象的代码需要在函数内部,如果需要,可以在 a 内部声明namespacestd此外,无论如何,向命名空间添加新内容是非法的。

此外,您不能以代码尝试的方式创建对象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;
}

推荐阅读