我的c ++文件未打开,为什么? [英] my c++ file is not opened , why?
问题描述
cout<<"enter name of file : " <<endl;
char nof[30] ;
for (int i=0;i<20;++i){
cin>>nof[i];
if (nof[i-1]=='x'){
if (nof[i]=='t'){
break;
}
}
}
fstream file1;
file1.open(nof);
if (file1.is_open()) cout<<"file is open"<<endl;
这是一个代码,应该使用用户的文件名来创建 但是我检查了它是否已打开,但没有打开,该怎么办?
that is a code which should take the name of file from user to create but i checked if it is opened and it is not , what to do ?
推荐答案
处理用户输入的方式使变量nof
成为正在运行的操作系统上的无效文件路径.这就是fstream::is_open()
返回false的原因.
The way you handle user input make variable nof
a invalid file path on your running os. That's why fstream::is_open()
return false.
for (int i=0;i<20; ++i){
cin >> nof[i];
if (nof[i-1]=='x'){
if (nof[i]=='t'){
break;
}
}
}
此代码需要用户输入,直到获得xt
.但是在C/C ++中,char*
或char[]
类型的有效字符串必须以\0
字符结尾.因此,如果您仍然喜欢处理输入的方式,请在中断循环之前将\0
附加到nof
的末尾.
This code takes user input until it gets xt
. But in C/C++, a valid string of char*
or char[]
type has to be end with \0
character. So if you still love the way you handling input, append \0
to the end of nof
before you break the loops.
for (int i=0;i<20; ++i){
cin>>nof[i];
if (nof[i-1]=='x'){
if (nof[i]=='t'){
nof[i+1]=0; //or nof[i+1]='\0' or nof[i+1]=NULL;
break;
}
}
}
但是我建议您改用std::string
和getline
,上面的方法很尴尬.
But I suggest you use std::string
and getline
instead, the above way is quite awkward.
std::string nof;
std::getline(std::cin, nof);
std::fstream file;
file.open(nof.c_str(), std::fstream::in | std::fstream::out);
这篇关于我的c ++文件未打开,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!