注册 登录
编程论坛 C++教室

为啥不能转化0?

leshui 发布于 2022-10-25 20:41, 1202 次点击
//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不可以?
1 回复
#2
rjsp2022-10-26 08:25
你自己的代码!如果转换结果是0的话则抛出异常
        if(!(result=boost::lexical_cast<unsigned>(s)))
            throw s;

他等同于
        result = boost::lexical_cast<unsigned>(s);
        if( result == 0 )
            throw s;
1