如何将变量插入到创建目录()

How do you insert a variable into CreateDirectory()

本文关键字:创建目录 插入 变量      更新时间:2023-10-16

有没有办法将字符串变量插入到CreateDirectory中?我希望它用 C: 创建一个目录,其中包含用户输入的名称。当我做类似的事情时

CreateDirectory ("C:\" << newname, NULL); 

我的编译器在"C:\"中给了我错误"运算符不匹配<<<<新名字'"

这是我的代码。问题出在无效的新游戏()。

#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <mmsystem.h>
#include <conio.h>

using namespace std;
int a;
string newname;
string savepath;
struct game
{
    string name;
    int checkpoint;
    int level;
};
void wait( time_t delay )
{
time_t timer0, timer1;
time( &timer0 );
do {
time( &timer1 );
} while (( timer1 - timer0 ) < delay );
}
void error()
{
    cout << "nError, bad input." << endl;
}
void options()
{
    cout << "No options are currently implemented." << endl;
}
void load()
{
    cout << "Load a Game:n";
}
//This is where I'm talking about.
void newgame()
{
    cout << "Name your Game:n";
    getline(cin,newname);
    cin.get();
    game g1;
    g1.name=newname;
    //I want it to create a dir in C: with the name the user has entered.
    //How can I do it?
    CreateDirectory ("C:\" << newname, NULL);

}
//This isn't the whole piece of code, just most of it, I can post the rest if needed
CreateDirectory (("C:\" + newname).c_str(), NULL);

您可以将std::stringoperator+ .或者,在您的情况下,您也可以使用 operator+ 将 C 字符串连接到std::string。结果是std::string.(不过要小心 - 你不能以这种方式将两个 C 字符串连接在一起。

但是,我怀疑CreateDirectory需要 C 字符串,而不是 std::string ,因此您需要使用 .c_str() 成员对其进行转换。

要使用流插入,您需要首先创建一个流:

std::ostringstream buffer;
buffer << "c:\" << newname;
CreateDirectory(buffer.str().c_str());