c - 如何处理从复杂输入(字符串)中提取双精度数
问题描述
祝大家有美好的一天,
我对 C 编程有点陌生,我偶然发现了一个问题,几天来一直在尝试正确解决,但仍然没有令人满意的结果。
我试图double
从用户以这种形式给出的输入中提取一些值{[ 5.1 ; 4 ], [15.3 ; -3.2] }
。我尝试了很多方法,到目前为止最好的方法是我将用户输入作为字符串读取,使用fgets()
循环for
,如果isdigit()
看到一个数字我将它存储在另一个字符串中,然后我检查数字后面是否有一个点,如果然后我把它放在数字后面的字符串中,依此类推。
真正的问题是当我想输出结果字符串并将其转换为我想要double
的时,strtod()
它只有在用户首先输入一些数字时才有效,但如果输入看起来像{ [ 2.5 ; 1 ] }
代码只是不关心并且什么都不做。任何帮助或见解将不胜感激,也许我采取了错误的方法?谢谢你。
我的代码
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#define STR_LEN 256
int main() {
char t1[STR_LEN], digits[STR_LEN], *dpt, per[2] = ".";
int i, digit, period;
double x;
fgets(t1, STR_LEN, stdin);
for (i = 0; i < strlen(t1); i++) {
digit = isdigit(t1[i]);
period = (t1[i + 1] == '.') ? 1 : 0;
if (digit) {
digits[i] = t1[i];
}
if (period == 1) {
strcpy(digits, digits);
strcat(digits, per);
}
}
x = strtod(digits, &dpt);
int testOutput = strlen(digits);
printf("%s %d %lf", digits, testOutput, x);
return 0;
}
解决方案
尝试这个:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct Pair {
double first;
double second;
struct Pair * tail;
};
void printPairs( const struct Pair * node ) {
if( node->tail ) {
printPairs( node->tail );
}
printf( "[ %3.2f ; %3.2f ]\n", node->first, node->second );
}
int main() {
const char * input = "some words before {[ 5.1 ; 4 ], [15.3 ; -3.2] } some words after";
struct Pair * head = NULL, * p = NULL;
char * err = NULL;
double first, second;
const char * s = strchr( input, '{' );
while( s ) {
s = strchr( s, '[' );
if( ! s ) {
break;
}
while( *s == ' ' || *s == '[' ) {
++s;
}
first = strtod( s, &err );
if( err && ( *err == ' ' || *err == ';' )) {
s = err + 1;
while( *s == ' ' || *s == ';' ) {
++s;
}
second = strtod( s, &err );
if( err && ( *err == ' ' || *err == ']' )) {
p = (struct Pair *)calloc( 1, sizeof( struct Pair ));
p->first = first;
p->second = second;
p->tail = head;
head = p;
}
else {
fprintf( stderr, "Parse error, space or ']' expected\n" );
exit( EXIT_FAILURE );
}
}
else {
fprintf( stderr, "Parse error, space or ';' expected\n" );
exit( EXIT_FAILURE );
}
}
printPairs( head );
}
输出:
[ 5.10 ; 4.00 ]
[ 15.30 ; -3.20 ]
推荐阅读
- python - 自定义字典键和值
- python - 从 CSS 选择器中排除 div
- php - 无法发送会话缓存限制器/无法修改标头信息
- r - 如何在 R 中预览 .Rd 文档文件?
- bash - 在远程主机上运行本地 bash 脚本
- python - 从相同索引的列表元素中选择随机整数并生成一个列表
- python-3.x - 如何在不使用 Json 的情况下从书籍 txt 文件制作字典?
- wxpython - 如何识别以 wxPython 结尾的文件?
- vhdl - Microblaze 的 bmm 文件中出现意外符号
- angularjs - AngularJS 中使用 ng-include 的页面渲染速度