如何在C中从这种类型的字符串中获取数字
在ANSI C中如何从该字符串中获取数字 我试着用strtok()把它分开: 我得到了这个:如何在C中从这种类型的字符串中获取数字,c,string,integer,strtok,atoi,C,String,Integer,Strtok,Atoi,在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, deli
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"
我想知道atoi(),但我不确定它是否能识别例如“13”作为一个数字 你也可以做同样的事情,把衣服脱到“;”但也可以将“”用于空格。将这个结果放入一个数组中,您可以在整个数组中使用atoi或任何您想要的东西。如果要将其放入二维数组中,可以将字符串拆分为“;”然后在该循环中,将每个整数拆分为数组中您想要的任何部分。不会编写代码,因为它看起来像家庭作业。一种方法是使用sscanf:
field[1][1] = 1
.
.
.
etc.
char*输入=。。。;
while(*输入){
输入+=';'==*输入;
int a,b,c,d,n=-1;
sscanf(输入,“%d%d%d%n”、&a、b、c、d和n);
if(n<0)
//解析错误
//已成功解析为a、b、c、d
输入+=n;
}
请注意,此处输入字符串保持不变。使用偶数空格作为分隔符。例如,在ur示例中,此代码将数字放入大小为4x4的2d数组中
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;
}
#包括
#包括
void main()
{
字符a[]=“1134;56778;9101112;2151400”;
int i=0,j=0,x;
整数数组[4][4];
字符*温度;
温度=标准温度(a,“;”);
做
{
数组[i][j]=atoi(温度);
如果(j==4)
{
i++;
j=0;
}
j++;
}while(temp=strtok(NULL,;”);
对于(i=0;这看起来像是一个家庭作业。这个程序是如何设置的?你怎么称呼它?请给出更多细节。
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;
}
#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");
}
}