質問

1 13 3 4; 5 6 7 8; 9 10 11 12; 2 15 14 0

How can I get numbers from this string in ANSI C?

I tried to separate it with strtok() :

char *vstup = argv[1];
char delims[] = ";";
char *result = NULL;
result = strtok( vstup, delims );  

while( result != NULL ) {
    printf( "result is \"%s\"\n", result );
    result = strtok( NULL, delims );
} 

and I got this:

result is "1 13 3 4"  
result is " 5 6 7 8"  
result is " 9 10 11 12"  
result is " 2 15 14 0"  

Now I don't know how to get numbers in integers and save them to two-dimensional field (matrix). I need something like this:

field[1][1] = 1
.
.
.
etc. 

I'm wondering about atoi(), but I'm not sure, if it would recognize for example "13" as one number..

役に立ちましたか?

解決

Use even space as delimiter. For example in ur case this code put the numbers in 2d array of size 4x4

#include<stdio.h>
#include<string.h>

void main()
{
char a[] = "1 13 3 4; 5 6 7 8; 9 10 11 12; 2 15 14 0";
int i=0 ,j=0 , x;
int array[4][4];
char *temp;
temp = strtok(a," ;");
do
{
    array[i][j] = atoi(temp);
    if(j == 4)
    {
        i++;
        j = 0;
    }
    j++;
}while(temp = strtok(NULL," ;"));

for(i=0; i<4; i++)
{
    for(j=0; j<4 ;j++)
    {
        printf("%d ",array[i][j]);
    }
    printf("\n");
}   
} 

他のヒント

You can do the exact same thing you did for stripping up to the ';' but instead also use ' ' for spaces. Place this result into an array and you can use atoi or whatever you want on the entire array. If you want to put it into a 2-d array you can split the string up to the ';' and then within that loop split each integer into whatever part of the array you want to. Won't write the code as it looks like homework.

One way is to use sscanf:

char* input = ...;
while(*input) {
    input += ';' == *input;
    int a, b, c, d, n = -1;
    sscanf(input, "%d %d %d %d%n", &a, &b, &c, &d, &n);
    if(n < 0)
        // parsing error
    // parsed successfully into a, b, c, d
    input += n;
}

Note, that the input string is left unchanged here.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top