How to Convert a Command-Line Argument to Int

How to convert a command-line argument to int?

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; simplest, but will treat any invalid number as 0:

#include <cstdlib>

int x = atoi(argv[1]);

The C way with input checking:

#include <cstdlib>

errno = 0;
char *endptr;
long int x = strtol(argv[1], &endptr, 10);
if (endptr == argv[1]) {
std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (*endptr) {
std::cerr << "Trailing characters after number: " << argv[1] << '\n';
} else if (errno == ERANGE) {
std::cerr << "Number out of range: " << argv[1] << '\n';
}

The C++ iostreams way with input checking:

#include <sstream>

std::istringstream ss(argv[1]);
int x;
if (!(ss >> x)) {
std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (!ss.eof()) {
std::cerr << "Trailing characters after number: " << argv[1] << '\n';
}

Alternative C++ way since C++11:

#include <stdexcept>
#include <string>

std::string arg = argv[1];
try {
std::size_t pos;
int x = std::stoi(arg, &pos);
if (pos < arg.size()) {
std::cerr << "Trailing characters after number: " << arg << '\n';
}
} catch (std::invalid_argument const &ex) {
std::cerr << "Invalid number: " << arg << '\n';
} catch (std::out_of_range const &ex) {
std::cerr << "Number out of range: " << arg << '\n';
}

All four variants assume that argc >= 2. All accept leading whitespace; check isspace(argv[1][0]) if you don't want that. All except atoi reject trailing whitespace.

Passing a integer through command line in C?

The signature for the main function in C would be this:

int main(int argc, char *argv[]);

argc is the number of arguments passed to your program, including the program name its self.

argv is an array containing each argument as a string of characters.

So if you invoked your program like this:

./program 10

argc would be 2

argv[0] would be the string program

argv[1] would be the string 10

You could fix your code like this:

#include <stdio.h>
#include <stdlib.h>
#define PI 3.1416
int
main (int argc, char *argv[])

{
double r,area, circ;

char *a = argv[1];
int num = atoi(a);

printf("You have entered %d",num);

r= num/2;
area = PI * r * r;
circ= 2 * PI * r;

printf ("A circle with a diameter of %d ", num);
printf ("has an area of %5.3lf cm2\n", area);
printf ("and a circumference of %4.2lf cm.\n", circ);

return (0);

}

You probably also want to add line breaks into your print statements for readability.

Command line argument to int in less then 3 LOC?

You can use std::atoi:

int size = std::atoi(argv[1]);

Beware that it provides awful error reporting - it just returns 0 is no conversion can be performed. A better alternative is std::stoi, which accepts an std::string and throws an exception on error:

int size = std::stoi(argv[1]); // note implicit conversion from const char * to std::string

C command line arguments to int

You can directly pass argv[2] to myatoi() or use a variable:

 char *str = argv[2];
int val=myatoi(str);

You are also better off adding an input check before using argv like:

if (argc != 3) {
printf("Expected 2 args\n");
exit(1);
}

Your myatoi() suffers the similar problems like the atoi() standard function -- lacks the ability to detect and report bad inputs. Consider what happens if argv[2] is "xyz123" for example.

How to read command-line arguments as integers instead of strings?

argv is an array of pointers to C strings. You need to convert the strings into integers first. You can do something like this:

int array_sum(int *array,  size_t size);
int main(int argc, char **argv){
int *num_arr = malloc((argc - 1) * sizeof *num_arr);

for (int i = 0; i < argc - 1; ++i)
num_arr[i] = atoi(argv[i+1]);

int sum = array_sum(num_arr, argc - 1);
printf("array_sum: %i\n", sum);

free(num_arr);
return 0;
}

The only way to make the code in main shorter is by moving the conversion loop into a separate function that returns the malloced pointer.

how to write Command-Line Arguments , and how to covert string to int in java

You have two choices - either add a second array, or count the positive numbers on the fly.

First solution - first transform the Strings to ints, and then count the positives ones:

public class count {
private static int countPositive(int[] elems) {
int positive = 0;
for (int i = 0; i < elems.length; i++) {
if (elems[i] > 0) {
positive++;
}
}
return positive;
}

public static void main(String[] args) {

int[] intArr = new int[args.length];
for (int i = 0; i < args.length; i++) {
intArr[i] = Integer.parseInt(args[i]);
}
System.out.println(countPositive(intArr));
}
}

Second solution - transform the Strings to ints one at a time, and count the positive ones:

public class count {
public static void main(String[] args) {
int positive = 0;
for (int i = 0; i < args.length; i++) {
if (Integer.parseInt(args[i]) > 0) {
positive++;
}
}
System.out.println(positive);
}
}

A bonus, third solution using Streams:

public class count {
public static void main(String[] args) {
System.out.println(Arrays.stream(args).mapToInt(i -> Integer.parseInt(i)).filter(i -> i>0).count());
}
}


Related Topics



Leave a reply



Submit