简体   繁体   中英

How to extract numbers from char or string?

This is my first question on this forum and it is rather tricky.

I am working on a problem in C where you are entering characters,until you enter the sign ! . Then you have to extract the numbers and print their sum.

The input is in the format : adasdas12fef 1 asdasdas43 da3 23adead

The output should be : 82 ( 12+1+43+3+23)

Note: The usage of string is forbidden.

I am sorry for the bad language.

If there are any questions about other details or usages, feel free to comment.

I think this will work for you :

#include <stdio.h>

int main(void) {
    // declear and initialize the variables
    char input[200];
    char c;
    int i = 0, j = 0, sum = 0, num = 0, next = 0;

    // get input until '!' is pressed
    while((c=fgetc(stdin)) != '!') {
        input[i] = c;
        i++;
    }

    // end string
    input[i] = '\0';

    // loop through the string
    // if numeric found, will add to sum.
    // for 2 numeric (one after another) will multiply
    // previous one with 10 and add with the current one
    for (j = 0; j < i; j++) {
        if (next == 1) {
            next = 0;
            num = input[j-1] - '0';
            num *= 10;
            num += (input[j] - '0');
            sum += num;
            continue;
        }

        if (input[j] >= '0' && input[j] <= '9') {
            if (input[j+1] >= '0' && input[j+1] <= '9') {
                next = 1;
            } else {
                sum += (input[j] - '0');
            }
        }
    }

    printf("sum: %d\n", sum);
}

Please do not ask for full code. I found the problem interesting, that's why I did it. Try first, then ask if you face any specific problem.

How about some pseudo code to get you started?

state = spaces
number = 0
Forever {
  Get ch
  if (ch == EOF or `!`) {
    if (state == num) print number
    break;
  }
  if (state == space) {
    if (ch is a digit) {
       number = digit
       state = num
    }
  } else {
    if (ch is a digit) {
       number = number * 10 + digit
    } else if (ch is a space) {
       print number
       state = space 
       number = 0
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM