创建与输入名称相同的文件

creating the file with the same name as input

本文关键字:文件 输入 创建      更新时间:2023-10-16
cout << "Enter your full name";
char* name ;
cin >> name;
  if( _mkdir("c:\names") == 0 ) {
     cout << "directory successfully created";
  }  else {
       cout << "there was a problem creating a directory";
     }

现在,我想在目录names中创建一个文件(.txt文件(,其名称与user的名称相同。我指的是用户在cin >> name;期间输入的名称。

我该怎么做?

ofstream writeName( "c:/names/????);---->问题

使用std::string而不是char*。事实上,您的代码具有未定义的行为。使用std::getline而不是>>。对于>>,只输入第一个以空格分隔的"单词"。然后,在std::string中组成完整的路径。标准字符串类支持串联,所以这应该很容易。

假设字符串是path

std::ofstream f( path.c_str() );

干杯&hth。,

您可以通过fopenofstream创建文本文件。

但是您为name输入的方式似乎是错误的。您没有为name分配空间。尝试使用mallocnew

char*指向一个字符。由于它没有初始化,它指向涅盘->未定义的bahavior

您可以尝试使用char name[MAX_LENGTH_FOR_YOUR_NAME]。这里最好使用std::string name