Home > Net >  How do i extract the numbers from this input format?
How do i extract the numbers from this input format?

Time:10-29

i need to "scan" exactly like the line i highlighted. how do i extract the numbers? Im at the start of the course so dont post overcomplicated solution i might not have studied yet.

Enter (House-cost, down-payment, savings, savings-annual-rate, mortgage-annual-rate, salary, fraction-saving, annual-raise, house-rent):

(600000, 0.15, 50000, 0.02, 0.03, 10000, 0.3, 0.03, 2000)

C LANGUAGE.

CodePudding user response:

how do i extract the numbers?

The easy approach is to read the line with fgets() and then parse with sscanf() and "%n" to record the offset of the scanning, if it got that far.

Use a format that is tolerant of white-space near the (,) separators.
"%lf" already consumes leading white-space.

  #define EXPECTED_SIZE 100
  char buffer[EXPECTED_SIZE * 2];  // Be generous in buffer size

  // Was a line successfully read?
  if (fgets(buffer, sizeof buffer, stdin)) {

    // Example code simplified to 3 variables
    double House_cost, down_payment, savings;
    int n = 0;
    sscanf(buffer, " (%lf ,%lf ,%lf ) %n",
        &House_cost, &down_payment, &savings, &n);
    // Did scanning reach the %n and was that the end of the line?
    if (n > 0 && buffer[n] == '\0') {
      Success();
    } else {
      Failed();
    }
  }

A good parser is ready to detect bad input. Do not assume input is well formatted.

CodePudding user response:

There are a set of C ANSI Standard library functions to convert character data to numeric data. These are in the stdlib.h header file and are atoi(), atof(), atol(), atoll(). These functions convert alpha to integer, floating point double, long integer and long long integer data types.

If not familiar with C language, reference online documentation available for the GNU C/C compiler...GNU C Run-Time Library Reference

GNU C Compiler and Language Reference

  • Related