我的c ++文件未打开,为什么? [英] my c++ file is not opened , why?

查看:101
本文介绍了我的c ++文件未打开,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 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::stringgetline,上面的方法很尴尬.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆