如何将命令行参数转换为int? [英] How to convert a command-line argument to int?

查看:1820
本文介绍了如何将命令行参数转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要得到一个参数,并将其转换为一个int。这是我的代码到目前为止:

  #include< iostream> 


使用namespace std;
int main(int argc,int argvx []){
int i = 1;
int answer = 23;
int temp;

//解码参数
if(argc <2){
printf(您必须提供至少一个参数\\\
);
exit(0);
}

//将其转换为int

}


解决方案

由于这个答案被某种程度上接受,因此会出现在顶部,虽然它不是最好的,其他答案和评论。



C方式;最简单,但会将任何无效的数字视为0:

  #include< cstdlib> 

int x = atoi(argv [1]);

输入检查的C方式:



<$ $ p> #include< cstdlib>

char * endptr;
long int x = strtol(argv [1],& endptr,10);
if(!* argv [1] || * endptr)
cerr<< 无效数<< argv [1]<< '\\\
';

输入检查的C ++方式:

  #include< sstream> 

istringstream ss(argv [1]);
int x;
if(!(ss>> x))
cerr<< 无效数<< argv [1]<< '\\\
';

这三个变体假设 argc> = 2


I need to get an argument and convert it to an int. Here is my code so far:

#include <iostream>


using namespace std;
int main(int argc,int argvx[]) {
    int i=1;
    int answer = 23;
    int temp;

    // decode arguments
    if(argc < 2) {
        printf("You must provide at least one argument\n");
        exit(0);
    }

    // Convert it to an int here

}

解决方案

Since this answer was somehow accepted and thus will appear at the top, although it's not the best, I've improved it based on the other answers and the comments.

The C way; easiest, but will treat any invalid number as 0:

#include <cstdlib>

int x = atoi(argv[1]);

The C way with input checking:

#include <cstdlib>

char *endptr;
long int x = strtol(argv[1], &endptr, 10);
if (!*argv[1] || *endptr)
    cerr << "Invalid number " << argv[1] << '\n';

The C++ way with input checking:

#include <sstream>

istringstream ss(argv[1]);
int x;
if (!(ss >> x))
    cerr << "Invalid number " << argv[1] << '\n';

All three variants assume that argc >= 2.

这篇关于如何将命令行参数转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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