将命令行输入放入数组并将此数组解析为两个新数组

时间:2014-12-02 19:01:09

标签: c arrays parsing command argv

我被告知要用适当的评论和我正在处理的实际代码重新制作。 我尝试接受命令行输入并将其放入数组中。我想将此数组解析为两个新数组。

问题是argv [1]是一个char *所以我遇到了转换成INT的问题。 我也无法弄清楚如何从argv [1]中取出每个元素(例如1010101)并将这些1和0放在一个数组中。一旦我搞清楚了,我将采用这个数组并在输入大于5时解析它。进入的命令行参数将是5长度或10长度。如果它是5我什么也不做,如果它是10我解析输入到两个数组。

#include <stdio.h>
#include <stdlib.h>


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


int i;
//starting using char * arrays in order to try to grab input from the char * argv[1] command line arg
char *aA[10] = {0};
char *aB[10] = {0};
char *aC[10] = {0}; 
char *s = '1';
char *k = '0';

//read in from command the command line.  Print the arguments and save
//the 1 and 0 inputs into an array.
//need to check for EOF and next lines
for (i = 0; i < argc; i++)
{
    if (argv[i] == (s | k)) //attempting to find a way to look at 1 and 0 as a char
    {
        aA[i] = argv[i]; //place the 1 or 0 into array aA
    }

    printf("arg %d: %s\n", i,  argv[i]);
}

printf("\n");

//print array aA to see if it caught all of the 1's and 0's from the command line argument
for (i = 0; i < 8; i++)
{
    printf("%s ", aA[i]);
}

//next check if array aA is 5 strlen or 10 strlen
//if 5, do nothing
//if 10, parse array aA into two arrays aB and aC
//aB gets a[0] a[2] a[4] a[6] a[8]
//aC gets a[1] a[3] a[5] a[7] a[9] 
//print the results of aB and aC to make sure aA was correctly parsed   


printf("\n");
return 0;

}

1 个答案:

答案 0 :(得分:1)

given a command line: myexecutable 10101   or myexecutable 1010101010

char originalArray[10] = {'\0'};
int array1[5] = {0};
int array2[5] = {0};
int i; // loop counter

if (2 == argc)
{ // then parameter exists
    if( (10 == strlen(argv[1])) || (5 == strlen(argv[1]) )
    { // then valid parameter length
        strncpy( originalArray, argv[1], strlen(argv[1]) );
    }

    else
    { // not valid parameter length
        // handle error
        exit( EXIT_FAILURE );
    }


    for( i=0; i<5; i++ )
    {
        if( ('1' == originalArray[i]) || ('0' == originalArray[i]) )
        { // then valid char 
            array1[i] = originalArray[i] - '0';
        }

        else
        { // invalid char in parameter
            // handle error
             exit( EXIT_FAILURE );
        } // end if
    } // end for


    if( 10 == strlen(originalArray) )
    { // then set second array
        for( i=5; i<10;i++ )
        {
            if( ('1' == originalArray[i]) || ('0' == originalArray[i]) )
            { // then valid character
                array2[i-5] = originalArray[i] - '0';
            }

            else
            { // invalid char in parameter
                // handle error
                exit( EXIT_FAILURE );
            } // end if
        } // end for
    } // end if