如何检查文本文件中的字符串是int,float还是none(字符串)?

时间:2015-11-30 06:24:52

标签: c

给出一个文本文件:

    123.33
    2
    1242.1
    99.9
    2223.11
    Hello
    22
    989.2
    Bye

我如何检查一行是整数还是浮点数或(无)字符数组?如果它是一个int然后将它放入intArray,如果它是double / float然后将它放入doubleArray,否则将它放入charArray。

FILE *file = fopen(argv[1], "r");
char line[100];

int intArray[100];
double doubleArray[100];
char charArray[100];

while(fgets(line, sizeof(line), file) != NULL){


}

2 个答案:

答案 0 :(得分:2)

这里的问题是在整数和浮点数之间进行区分。带小数点或指数或两者的数字应视为浮点数。

数字转换的旧标准函数对于整数是atoi,对于浮点数是atof。这些将解析字符串,但最终可能只解析它一半。 atoi("123.4")被解析为123.另一方面,atof(118)将(正确)产生浮点数118.0。

C99提供更高级的解析函数strtol(对于长整数)和strtod(对于双精度)。这些函数可以返回指向未转换的第一个字符的尾指针,这样可以查明字符串是否已完全解析。

有了这个,我们可以编写一些简单的包装函数来告诉我们字符串是表示整数还是浮点数。确保首先测试整数,以便"23"被正确地视为整数:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int parse_double(const char *str, double *p)
{
    char *tail;

    *p = strtod(str, &tail);

    if (tail == str) return 0;
    while (isspace(*tail)) tail++;
    if (*tail != '\0') return 0;
    return 1;
}

int parse_long(const char *str, long *p)
{
    char *tail;

    *p = strtol(str, &tail, 0);

    if (tail == str) return 0;
    while (isspace(*tail)) tail++;
    if (*tail != '\0') return 0;
    return 1;
}

int main(void)
{
    char word[80];

    while (scanf("%79s", word) == 1) {
        double x;
        long l;

        if (parse_long(word, &l)) {
            printf("Integer %ld\n", l);
            continue;
        }

        if (parse_double(word, &x)) {
            printf("Double %g\n", x);
            continue;
        } 

        printf("String \"%s\"\n", word);
    }

    return 0;
}

答案 1 :(得分:0)

你可以做这样的事情

FILE *file = fopen(argv[1], "r");
char line[100];

int intArray[100];
double doubleArray[100];
char charArray[100];

int intNum;
float floatNum;
int i = 0; //index for intArray
int j = 0; //index for floatArray

while(fgets(line, sizeof(line), file) != NULL){
   intNum = atoi(line); 
  if (num == 0 && line[0] != '0') { //it's not an integer
     floatNum = atof(line);
     if(/* to put test condition for float */) {  //test if it is a float
         //add to floatArray    
     } else {
        //or strcpy to charArray accordingly
     }
  } else { //it's an integer
     intArray[i++] = intNum; //add to int array
  }       
}