C++ 奇怪的字符串结果

C++ 奇怪的字符串结果,c++,string,file,C++,String,File,我的程序应该打开一个文件,使用argv[1]从命令行检索文件路径 然后我尝试使用fopen打开文件,但我的程序崩溃了,因为我使用的文件路径不包含双反斜杠,所以fopen无法工作 我曾尝试编写自己的转换函数,并使用print检查结果,乍一看效果不错 问题是,当我使用返回的const char*作为参数时,它会给我一个奇怪的结果。。我的代码: #include <stdio.h> #include <stdlib.h> #include <string> co

我的程序应该打开一个文件,使用
argv[1]
从命令行检索文件路径

然后我尝试使用fopen打开文件,但我的程序崩溃了,因为我使用的文件路径不包含双反斜杠,所以fopen无法工作

我曾尝试编写自己的转换函数,并使用print检查结果,乍一看效果不错

问题是,当我使用返回的const char*作为参数时,它会给我一个奇怪的结果。。我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string>


const char* ConvertToPath(std::string path)
{
    std::string newpath = "";
    for(unsigned int i = 0; i < path.length(); ++i)
    {
        if(path[i] == '\\')
        {
            newpath += "\\\\";
        }
        else
        {
            newpath += path[i];
        }
    }
    printf("%s \n", newpath.c_str());
    return newpath.c_str();
}

bool OpenDBC(const char* path)
{
    const char* file = ConvertToPath(path);
    printf("%s \n", file);
    FILE* dbc = fopen(file, "rbw");
    if (!dbc)
        return false;
    return true;
}

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        printf("Error, expected DBC file.");
        getchar();
        return -1;
    }

    if (!OpenDBC(argv[1]))
    {
        printf("There was an error opening the DBC file.");
        getchar();
        return -1;
    }
    getchar();
    return 0;
}

所以看起来
const char*file
只包含文件路径的1个字符,为什么?

您根本不需要ConvertToPath函数。双反斜杠仅在字符串文本中需要。永远不要使用std::string之类的变量。

我在Linux上编译了您的代码,无法复制您的结果

运行
/filereader“D:\\eaccessment.dbc”
会导致

D:\\Achievement.dbc
D:\\Achievement.dbc
D:\\\\Achievement.dbc 
D:\\\\Achievement.dbc 
运行
/filereader“D:\\\\Achization.dbc”
会导致

D:\\Achievement.dbc
D:\\Achievement.dbc
D:\\\\Achievement.dbc 
D:\\\\Achievement.dbc 

后者是您想要的,因为需要转义命令行参数。然后可以删除依赖于未定义行为的
ConvertToPath

,从本地字符串返回
c_str()
是一个非常糟糕的主意。只需返回字符串,并从内部调用
c_str()
@Chnossos的注释是正确的,但我也很好奇这句话:“我的程序崩溃,因为我使用的文件路径不包含双反斜杠,所以fopen无法工作”。除非在程序的源代码中指定了路径,否则通常不需要转义反斜杠。您根本不需要
ConvertToPath
,只需调用
fopen(argv[1])
即可查看结果。未定义的行为可以以多种方式表现: