c - 如何在C中从这种类型的字符串中获取数字

标签 c string integer strtok atoi

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/

相关文章:

c - 从C中的文件中读取字符串

mysql - 如何在没有mysql_free_result(res)的情况下在c中运行查询

c 字符串数组中的指针

c++ - 控制 DLL 中代码的可能方法

c - "#include"C 程序中作为 char[] 的文本文件

python - 如何查找整数中的数字长度?

c# - 你如何在 C# 中进行 *integer* 求幂?

c# - 可空类型 "int?"(包括问号)的默认值是多少?

javascript - 给一串html添加粗体标签

java - 十六进制转换为 EBCDIC