Good day! The problem says to display all numbers from the line. I read the number x by means of atof and "jump over" it with the help of sprintf into the buffer which returns the number of characters in the number x - then I change the position of the pointer. There is a condition to exit the cycle. Tell me, please, what is the root problem of my code, which instead of outputting all real numbers from the entered string is looped through. Is it possible to correct this fragment - or is the idea co sprintf inherently wrong? Thanks for attention.

#include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> int main(void){ char str[50]; char buffer[50]; double x; puts("enter a string: \n"); fgets(str, 50, stdin); str[strlen(str) - 1] = '\0'; //print all doubles from string; char* strptr = str; while(*strptr != '\0'){ if(isdigit(*strptr)){ x = atof(strptr); printf("%f\n", x); strptr = strptr + (sprintf(buffer, "%f", x)); } else strptr++; } return 0; } 

    1 answer 1

    You can see the problem if you run the following demo program.

     #include <stdio.h> int main( void ) { double x = 1.2; char buffer[50]; int n = sprintf(buffer, "%lf", x); puts(buffer); printf("%d\n", n); } 

    Output of the program to the console

     1.200000 8 

    As can be seen from the output, the number displayed by the number of fractional signs does not correspond to the original number. As a result, the pointer may not have the correct value in the loop.

    Instead of the approach you use, it is better to use the approach based on the use of the strtod function, which is declared in the <stdlib.h> header file as follows

     double strtod(const char * restrict nptr, char ** restrict endptr); 

    Below is a demonstration program that uses this feature.

     #include <stdlib.h> #include <stdio.h> #include <stype.h> int main( void ) { char str[] = "abc1.2def34ghi54.78j"; puts(str); for ( char *p = str; *p; ) { if (isdigit((unsigned char)*p)) { char *q; double x = strtod(p, &q); printf("%lf ", x); p = q; } else { ++p; } } } 

    The output of the program to the console:

     abc1.2def34ghi54.78j 1.200000 34.000000 54.780000 

    In your program, you could also add a check for the presence of a number sign, that is, if one of the characters '-' or '+' , followed by a number. In general, floating-point constants can also be given in hexadecimal format, but I think you do not need it.