[英]Taking path to file from variable in C, C++
I'm doing a little project using C, C++ and dirent.h
.我正在使用 C、C++ 和
dirent.h
做一个小项目。 I want to ask if its possible to take a path to a folder/file from a variable:我想问一下是否可以从变量中获取文件夹/文件的路径:
string fileName;
cout << "Create new file" << endl;
cin>>fileName;
CreateDirectory(documentLocation.c_str()+fileName.c_str(), NULL);
documentLocation
is my variable I gave at the beginning of the program where I want to create a new directory. documentLocation
是我在程序开始时提供的变量,我想在其中创建一个新目录。 Adding fileName
, I want to create a new directory in this folder.添加
fileName
,我想在这个文件夹中创建一个新目录。 But I get an error:但我收到一个错误:
expression must have integral or enum type
表达式必须具有整数或枚举类型
You can't use +
to concatenate C strings.您不能使用
+
连接 C 字符串。 Concatenate the std::string
s first, then get the C string from that.首先连接
std::string
s,然后从中获取 C 字符串。
CreateDirectory((documentLocation + fileName).c_str(), NULL);
c_str()
returns a const char *
, so in c_str()
返回一个const char *
,所以在
documentLocation.c_str()+fileName.c_str()
You try to add two const char *
, which does not work.您尝试添加两个
const char *
,这不起作用。
std::string
overloads the +
operator: std::string
重载+
运算符:
std::string path = documentLocation + fileName;
CreateDirectory(path.c_str(), NULL);
First add (concatenate) the two strings, then take the c_str()
of the result.首先将两个字符串相加(连接),然后取结果的
c_str()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.