免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1990 | 回复: 2
打印 上一主题 下一主题

[C++] 为什么总是说不能打开文件 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2016-05-05 21:36 |只看该作者 |倒序浏览
有哪位大神看一下吗?
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <stdexcept>
  5. #include <string>
  6. using namespace std;
  7. void readIntergerFile(const string& filename,vector<int>& dest)throw(invalid_argument,runtime_error)
  8. {
  9.         ifstream in;
  10.         int temp;
  11.         in.open(filename.c_str());//这个函数,我查了一下是返回const string指针,应该可以这么用吧
  12.         if(in.fail())
  13.         {
  14.                 string error="fail to open file"+filename;//总是说不能打开文件
  15.                 throw invalid_argument(error);
  16.         }
  17.         while(in>>temp)
  18.         {
  19.                 dest.push_back(temp);
  20.         }
  21.         if(in.eof())
  22.         {
  23.                 in.close();
  24.         }else{
  25.                 string error ="unable to read file";
  26.                 throw runtime_error(error);
  27.         }
  28. }
  29. int main(){
  30.         vector<int> dest;
  31.         const string filename="a.txt";
  32.         try{readIntergerFile(filename,dest);
  33.         }catch(invalid_argument& e){
  34.                 cerr<<e.what()<<endl;
  35.                 exit(1);
  36.         }catch(runtime_error& e){
  37.                 cerr<<e.what()<<endl;
  38.                 exit(1);
  39.         }
  40.         for(unsigned int i=0;i<dest.size();i++)
  41.         {
  42.                 cout<<dest[i]<<" ";
  43.         }
  44.         cout<<endl;
  45.         return (0);
  46. }
复制代码

论坛徽章:
12
2015年辞旧岁徽章
日期:2015-03-03 16:54:1515-16赛季CBA联赛之同曦
日期:2017-03-17 19:13:162016科比退役纪念章
日期:2016-11-07 08:28:12luobin
日期:2016-06-17 17:46:36wusuopu
日期:2016-06-17 17:43:4515-16赛季CBA联赛之福建
日期:2016-01-14 12:49:22程序设计版块每日发帖之星
日期:2015-12-13 06:20:00程序设计版块每日发帖之星
日期:2015-06-08 22:20:00程序设计版块每日发帖之星
日期:2015-06-08 22:20:002015年亚洲杯之科威特
日期:2015-03-24 14:21:272015年迎新春徽章
日期:2015-03-04 09:57:092016科比退役纪念章
日期:2018-04-10 16:20:18
2 [报告]
发表于 2016-05-06 08:46 |只看该作者
文件是新建还是打开?有没有权限?

论坛徽章:
0
3 [报告]
发表于 2016-05-06 10:35 |只看该作者
文件有的,权限应该也没有限制。用fail()发现filename为空,只打印了fail to open file,如果改为in.isopen(),打印出来fail to open file a.txt。好奇怪回复 2# VIP_fuck


   
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP