1 13 3 4; 5 6 7 8; 9 10 11 12; 2 15 14 0
如何从 ANSI C 字符串中获取数字?
我尝试用 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 );
}
我得到了这个:
result is "1 13 3 4"
result is " 5 6 7 8"
result is " 9 10 11 12"
result is " 2 15 14 0"
现在我不知道如何获取整数中的数字并将它们保存到二维字段(矩阵)。我需要这样的东西:
field[1][1] = 1
.
.
.
etc.
我想知道 atoi(),但我不确定它是否会将“13”识别为一个数字..
最佳答案
使用偶数空格作为分隔符。例如,在你的例子中,这段代码将数字放入大小为 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");
}
}
关于c - 如何在C中从这种类型的字符串中获取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14060805/