![](/img/trans.png)
[英]How to turn an array of integers into a permutation and count the loops in it?
[英]How to turn an array from command line into an array of integers?
我想知道如何將{33,44,77,88}
或{10,20,30}
等數組作為命令行參數給定,並將它們從char轉換為整數,然后最后將它們放入整數數組。
我一直在找幾個小時,但找不到一個示例,他們從命令行獲取數組並將其轉換為整數數組。
這就是我在命令行FOO {33,44,77,88} {10,20,30}
放置的內容FOO {33,44,77,88} {10,20,30}
我的前4行如下所示。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
傳遞命令行參數會將它們作為字符串(僅作為字符串)傳遞。 因此,您的argv
數組將如下所示: argv = {"./prog", "FOO", "{33,44,77,88}", "{10,20,30}"};
。 這意味着您的程序將需要解析傳入的數組,以便將其轉換為整數數組。 嘗試使用諸如strtok
函數基於分隔符來解析字符串。 然后,一旦獲得了單個數字,即已解析為“ 33”,則可以使用atoi
將此字符串轉換為整數。 您將需要手動構建陣列。
以下代碼將解釋以'{'開頭的所有參數,並以逗號分隔的任何數字都將被拉出。
#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");
}
}
}
樣本輸出:
./array-args '{ 1, 2, 3 }'
Processing '{1, 2, 3}'
Got Array: { 1, 2, 3 }
我沒有100%地理解您的問題,但是您所提供的一切的實現都會像這樣
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; }
編譯輸出:
〜/ c ++實踐> g ++ args.cpp〜/ c ++實踐> ./a.out {33,44,77,88} {10,20,30}
./a.out
33
44
77
88
10
20
30
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.