大家好,
我是 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 ]