| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 823 人关注过本帖
标题:为啥不能转化0?
只看楼主 加入收藏
leshui
Rank: 2
等 级:论坛游民
威 望:1
帖 子:7
专家分:17
注 册:2022-10-24
结帖率:50%
收藏
已结贴  问题点数:20 回复次数:1 
为啥不能转化0?
//mn.cpp
#include <iostream>
#include <exception>
#include <string>
#include "boost/lexical_cast.hpp"
#include <unistd.h>
#include <cstdlib>
using namespace std;
extern char *optarg;
string help="use:./程序名 -r数字.\n";
unsigned tryfunc(char *s)
{
    unsigned result = 999;

    try {
       // result = boost::lexical_cast<unsigned>( s );
       // if( result == 999)
       if(!(result=boost::lexical_cast<unsigned>(s)))
            throw s;
    }
    catch( const std::exception& e ) {
        std::cout << "------exception &e-------------wrong: " << e.what() << std::endl;
        std::cout<<help<<endl;
        exit(EXIT_FAILURE);
    }
    catch( const char* s ) {
        std::cout << "------char *optarg-------------wrong: " << s << std::endl;
        std::cout<<help<<endl;
        exit(EXIT_FAILURE);
    }
    catch( ... ) {
        std::cout << "----- -------------wrong: " << "other exception" << std::endl;
        std::cout<<help<<endl;
       exit(EXIT_FAILURE);
    }

    return result;
}


int main(int argc,char *argv[])
{  
    int opt,rmint=5;
   
    while ((opt = getopt(argc, argv, ":r:")) != -1)
  {
   switch (opt)
     {
     case 'r':
     rmint=tryfunc(optarg);
     break;
     default: /* '?' */
     std::cout<<help<<endl;
     return 0;
      }
    }
    std::cout<<"you input optarg:"<<rmint<<endl;
 }
 

wei@wei:~/bin$ ./mn -r0
------char *optarg-------------wrong: 0
use:./程序名 -r数字.

wei@wei:~/bin$ ./mn -r1
you input optarg:1
wei@wei:~/bin$
#为啥1可以转,0不可以?
搜索更多相关主题的帖子: cout std include result help 
2022-10-25 20:41
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9007
专家分:53942
注 册:2011-1-18
收藏
得分:20 
你自己的代码!如果转换结果是0的话则抛出异常
        if(!(result=boost::lexical_cast<unsigned>(s)))
            throw s;

他等同于
        result = boost::lexical_cast<unsigned>(s);
        if( result == 0 )
            throw s;
2022-10-26 08:25
快速回复:为啥不能转化0?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.067796 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved