为什么这个 .c_str() 看起来损坏了,为什么输出奇怪的字符?

问题描述 投票:0回答:1

我正在尝试使用 FuzzyLite C++ 库加载一个

.fis
文件并在 C++ 代码中使用它。我正在使用 C++ 14、Visual Studio 17.5.0 和 Visual C++ 2022。

按照入门指南,它将是:

#include <iostream>
#include <fl/Headers.h>
#include <fstream>

int main()
{
    const std::string filePath = "C:\\Users\\me\\fuzzyLogic\\rules.fis";

    fl::Engine* engine = new fl::Engine;

    try
    {
        engine = fl::FisImporter().fromFile(filePath);
    }
    catch (fl::Exception& e)
    {
        std::cerr << e.what() << std::endl; 
    }

    std::string status;
    if (not engine->isReady(&status))
        throw Exception("[engine error] engine is not ready:n" + status, FL_AT);
    else 
        std::cout << "ok" << std::endl;
}

我下载了完整的库源代码并使用

build.bat
在发布模式下编译它。然后尝试运行上面的代码但出现错误:

[file error] file <> could not be opened
{at \src\imex\Importer.cpp::fl::Importer::fromFile() [line:31]}

Visual Studio 调试器抛出这个:

Exception thrown at 0x00007FFD5C55FE7C in FuzzyLiteTest.exe: Microsoft C++ exception: fl::Exception at memory location 0x0000009F9539F5B0.
Exception thrown: read access violation.
**_Pnext** was 0xFFFFFFFFFFFFFFFF.

然后我在第 31 行打开

Importer.cpp
,它正在检查是否可以从路径打开阅读器:

Engine* Importer::fromFile(const std::string& path) const {
        std::ifstream reader(path.c_str());
        if (not reader.is_open()) {
            throw Exception("[file error] file <" + path + "> could not be opened", FL_AT);
        }
        std::ostringstream textEngine;
        std::string line;
        while (std::getline(reader, line)) {
            textEngine << line << std::endl;
        }
        reader.close();
        return fromString(textEngine.str());
}

好吧,所以我想我应该尝试以下方法:

  • 对文件路径使用字符串文字:没有用。
  • 使用相对文件路径:没用。
  • 任何与文件路径相关的东西都不起作用,因为文件没问题,我可以使用其他任何东西访问它的内容,比如
    fstream
    .

所以我改变了

Importer
来打印出它接收到的字符串:

Engine* Importer::fromFile(const std::string& path) const {
        std::cout << "path: " << path << '\n';
        std::cout << "path.c_str(): " << path.c_str() << '\n';
        std::ifstream reader(path.c_str());
        if (not reader.is_open()) {
            throw Exception("[file error] file <" + path + "> could not be opened", FL_AT);
        }
        std::ostringstream textEngine;
        std::string line;
        while (std::getline(reader, line)) {
            textEngine << line << std::endl;
        }
        reader.close();
        return fromString(textEngine.str());
}

重建图书馆,我再次尝试运行。然后得到这个输出:

path:
path.c_str(): ©÷9òƒ
[file error] file <> could not be opened
{at \src\imex\Importer.cpp::fl::Importer::fromFile() [line:33]}

它看起来已损坏或类似的东西。我尝试在源文件中搜索,但也找不到传递路径的任何地方。有什么线索吗?这是我在做的事吗?

c++ fuzzy-logic c-str
1个回答
0
投票

我发现了问题:不兼容的项目和库配置。我正在使用在发布模式下编译的库,而我的项目处于调试模式。他们需要处于相同的模式。

更多信息:这里

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