gpt4 book ai didi

c++ - 在 C++ 中将字符数组添加到常量字符数组的正确方法是什么?

转载 作者:行者123 更新时间:2023-11-30 00:53:02 27 4
gpt4 key购买 nike

在 C++ 中将字符数组添加到常量字符数组的正确方法是什么?

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
int pathSize = 0;
char* pathEnd = &argv[0][0];
while(argv[0][pathSize] != '\0') {
if(argv[0][pathSize++] == '/')
pathEnd = &argv[0][0] + pathSize;
}
pathSize = pathEnd - &argv[0][0];
char *path = new char[pathSize];
for(int i = 0; i < pathSize; i++)
path[i] = argv[0][i];
cout << "Documents Path: " << path + "docs/" << endl; // Line Of Interest
delete[] path;
return 0;
}
This code outputs: Documents Path: �\Using 'path' instead of '*path' will give me the compile error: invalid operands of types ‘char*’ and ‘const char [6]’ to binary ‘operator+’

最佳答案

我可以建议使用 C++ 开始,然后(提升)文件系统以获得最大 yield :

#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main(int argc, const char *argv[])
{
const std::vector<std::string> args { argv, argv+argc };

path program(args.front());
program = canonical(program);
std::cout << (program.parent_path() / "docs").native();
}

这将使用平台的路径分隔符,了解如何翻译“有趣”的路径(例如包含 ..\..\ 或 UNC 路径)。

关于c++ - 在 C++ 中将字符数组添加到常量字符数组的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17577898/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com