检查char array []是否包含int,float或double值,并将值存储到相应的数据类型

时间:2011-06-28 05:30:21

标签: c

在C编程中,如何检查char array[]是否包含intfloatdouble值,还是使用相应的数据类型存储值?

例:
如果char array[]包含100 - 其int值,则应存储在int a中。  如果char数组包含10000.01float值,则应存储在float b中。

6 个答案:

答案 0 :(得分:2)

在C中,与其他语言不同,您必须在编译时定义变量的类型。因此,如果你有一个char变量(或char数组),你有char而不是int而不是float而不是double。

答案 1 :(得分:2)

由于无法在运行时定义变量类型,因此您仍需要在编译时定义正确数据类型的变量。如果这不是问题,您可以扫描字符串并查找小数分隔符以确定它是浮点值还是整数值。但也许不是最强大的方法: - )

答案 2 :(得分:2)

在数组中存储混合类型的唯一方法是使用指针数组。

您需要使用结构或联合来存储每个结构或结合:

#define TYPE_INT 1
#define TYPE_FLOAT 2
#define TYPE_STRING 3

typedef struct  {
  int type;
  void *ptr;
} object;

object* mkobject( int type, void * data ){
  object * obj = (object*)malloc(COUNT*sizeof(object))
  obj->type = type;
  obj->ptr = data;
  return obj;
}

不使用上述内容可以存储类型信息

void * intdup( int original ) {
  int * copy = (int*) malloc(1*sizeof(int));
  *copy = original; 
  return (void*) copy;
}

void * floatdup( float original ) {
  float * copy = (float*) malloc(1*sizeof(float));
  *copy = original; 
  return (void*) copy;
}

int COUNT = 3;
objects** objectlist = (object**)malloc(COUNT*sizeof(object*))

// -- add things to the list
int a_number = 2243;
float a_float = 1.24;
char* a_string = "hello world"; 


objectlist[0] = mkobject( TYPE_STRING, strdup(a_string) );
objectlist[1] = mkobject( TYPE_INT, intdup(a_number) );
objectlist[2] = mkobject( TYPE_FLOAT, intdup(a_float) );


// iterate through a list

for ( int x = 0; x < COUNT; x++ ){

   switch( objectlist[x]->type ){

      case TYPE_STRING:
       printf("string [%s]\n",(char*) objectlist[x]->ptr );
       break;
      case TYPE_FLOAT:
       printf("float  [%f]\n", *(float*) objectlist[x]->ptr );
       break;
      case TYPE_INT:
       printf("int    [%d]\n", *(int*) objectlist[x]->ptr );
       break;
      default;
       printf("unintialized object\n");
       break;

   }

}

答案 3 :(得分:1)

我认为你想使用union(根据我对你答案的理解)。

union {
   char a[4];
   float b;
   int c;
} dude;
// ...
union dude woah;
woah.a = "abc";
puts(a);
woah.b = 4.3;
printf("%f\n", woah.b);
woah.c = 456;
printf("%d\n", woah.c);

答案 4 :(得分:1)

如果您存储的值如下:

"100.04"

在char数组中或类似的东西你可以这样做来检查数字是否有小数:

double check = atof(theChar);

if (check % 1 > 0) {
    //It's a real number
}
else {
    //It's more specifically an integer
}

如果这就是你的意思。你的问题对我来说有点不清楚。

虽然这不是真正的类型检查,但它只是测试事物是否有小数或者没有...就像其他人说过你不能这样做因为char *是在编译期间而不是在运行时定义的并且无法改变。

答案 5 :(得分:1)

假设数字是浮点数并使用strtod()

如果转换有效,则数字可以是整数。检查限制和接近正确的整数,如果确定则再次转换。

伪代码

char *input = "42.24";
char *err;
errno = 0;
double x = strtod(input, &err);
if (errno == 0) {
    /* it's (probably) a floating point value */
    if ((INT_MIN <= x) && (x <= INT_MAX)) {
        if (fabs(x - (int)x) < 0.00000001) {
            /* It's an integer */
            int i = x;
        }
    }
} else {
    /* deal with error */
}