[英]How to check if a string from a text file is an int, or float, or none(string)?
给定一个文本文件:
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){
}
这里的问题是区分整数和浮点数。 具有小数点或指数或两者兼有的数字应视为浮点数。
用于数字转换的旧标准函数是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;
}
你可以做这样的事情
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.