Reputation: 55
I'd like to know how I can turn arrays such as {33,44,77,88}
or {10,20,30}
, that are given given as command line arguments, and turn them from a char to an integer and finally put them into an array of integers.
I've been looking for hours and I cannot find an example where they get the array from the command line and turn it into an integer array.
This is what I had placed at the command line FOO {33,44,77,88} {10,20,30}
My first 4 lines look like this.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
Upvotes: 0
Views: 2159
Reputation: 2896
The following code will interpret any arguments starting with '{' and pull any numbers out that are comma delimited.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
long int* processArray(char* input, int* lng){
int length = 0, i = 0;
while (input[i] != '\0'){
if (input[i] == ',') length ++;
i++;
}
if (length > 0) length ++;
input++;
int j = 0;
long int * out = malloc(length * sizeof(long int));
while(*input != '}'){
while(*input != '\0' && !isdigit(*input)) input++;
if (!isdigit(*input)) break;
out[j++] = strtol(input, &input, 10);
}
*lng = j;
return out;
}
int main(int argc, char ** argv){
int i;
for ( i = 0; i < argc; i++){
// check for variables that look like arrays
if (argv[i][0] == '{'){
printf("Processing '%s'\n", argv[i]);
int l, j;
long int * variables = processArray(argv[i], &l);
printf("Got Array: { ");
for (j = 0; j < l; j++){
printf("%ld%s", variables[j], j == l-1? "" : ", ");
}
printf(" }\n");
}
}
}
Sample output:
./array-args '{ 1, 2, 3 }'
Processing '{1, 2, 3}'
Got Array: { 1, 2, 3 }
Upvotes: 1
Reputation: 321
i didnt understand your question to 100% but the implementation of what ever you gave will be like this
args.cpp:
#include<iostream>
using namespace std;
int main(int argc, char *argv[])
{
for (int i = 0; i < argc; ++i)
{
std::cout << argv[i] << std::endl;
}
return 0;
}
compilation and output :
~/c++practise>g++ args.cpp ~/c++practise> ./a.out {33,44,77,88} {10,20,30}
./a.out
33
44
77
88
10
20
30
Upvotes: -1
Reputation: 81
Passing in command-line arguments will pass them in as strings and only strings. Therefore, your argv
array will look like this: argv = {"./prog", "FOO", "{33,44,77,88}", "{10,20,30}"};
. This means that your passed in array will need to be parsed by your program in order to convert it into an integer array. Try using functions like strtok
to parse a string based on a delimiter. Then, once you get the individual numbers, i.e. you have parsed "33", you can use atoi
to convert this string into an integer. You will need to build your array up manually.
Upvotes: 2