创建与输入同名的文件
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文件),其名称与用户
的名称相同。我的意思是用户在 cin >> 期间输入的名称。名称;
。
我该怎么做?
ofstream writeName("c:/names/??????);
----> 问题
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";
}
Now i want to create a file ( a .txt file ) in the directory names
with the same name as the name of the user
. I mean the name which the user entered during cin >> name;
.
How can i do this ?
ofstream writeName( "c:/names/????);
----> PROBLEM
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
std::string
而不是char*
。因为您的代码具有未定义的行为。使用std::getline
而不是>>
。对于>>
,仅输入第一个以空格分隔的“单词”。然后,在std::string
中编写完整路径。标准字符串类支持连接,所以这应该很容易。比如说,如果该字符串是
path
,Cheers &呵呵,
Use
std::string
instead ofchar*
. As it is your code has Undefined Behavior. Usestd::getline
instead of>>
. With>>
only the first whitespace-separated "word" is input. Then, compose the full path in astd::string
. The standard string class supports concatenation, so this should be easy.Say, if that string is
path
,Cheers & hth.,
您可以通过
fopen
文件或使用ofstream
创建文本文件。但是您输入
name
的方式似乎是错误的。您没有为name
分配空间。尝试使用malloc
或new
You can create a text file by
fopen
ing the file or withofstream
.But your way of taking input for
name
seems wrong. You didn't allocate space forname
. Try usingmalloc
ornew
char*
指向一个字符。由于它没有初始化,所以它指向涅槃-> 未定义的行为。您可以尝试使用
字符名称[MAX_LENGTH_FOR_YOUR_NAME]
。最好在这里使用std::string name
。The
char*
points to one char. Since it is not initialized it points to nirvana -> undefined bahavior.You can try to use
char name[MAX_LENGTH_FOR_YOUR_NAME]
. It's better to use astd::string name
here.