Home > Software design >  Extract integers from a character string in C
Extract integers from a character string in C

Time:10-19

I'm doing an assignment where I have to extract numbers from a string put in by the user. I am having a very hard time on how to extract single digits and multiple digits from a string that as input can have anything, something like '4 33 coding 2 22is4fun2todo'. How can I extract these integers from this string and store the numbers in a separate array? I now have the following but it's not working:

#include <stdio.h>  // endables input/output commands
#include <stdlib.h> // enables standard library of functions

// main
int main(int argc, char *argv[]) {

char input[1000];      
    for (int i = 0; ; i  ) {
        scanf("%s" , &input[i]);
        if ('\n') {
            break;
        }
    }
int lengthInput;
lengthInput = strlen(input);
int number[lengthInput];

for (int i = 0; i < lengthInput; i  ) {
    if ((input[i] >= '0') && (input[i] <= '9' - '0')) {
        input[i] = number;
    }
}
    return 0;
}

CodePudding user response:

It is not necessary to read the input string into a char array.
The scanset %1[\n] will scan one character that is a newline.
The scanset %*[^- 0123456789\n] will scan and discard everything that is not a digit, , - or newline.
scanf returns the number of items successfully scanned, 0 if nothing matches the format specifier or EOF for End Of File.

#include <stdio.h>
#include <limits.h>

#define SIZE 1000

int main ( void) {
    int count = 0;
    int scanned = 0;
    int input[SIZE] = { 0};
    char newline[2] = "";

    printf ( "enter a string\n");
    while ( count < SIZE) {
        if ( 1 == scanf ( "%1[\n]", newline)) { // scan for newline
            break;
        }
        if ( 1 != ( scanned = scanf ( "%d", &input[count]))) { // scan for integer
            if ( EOF == scanned) {
                break;
            }
            scanf ( "%*[^- 0123456789\n]"); // scan and discard up to next integer
        }
        else {
              count;
        }
    }

    for ( int show = 0; show < count;   show) {
        printf ( "%d\n", input[show]);
    }

    return 0;
}

CodePudding user response:

Read about it here. There's a detailed description given in the blog.

  •  Tags:  
  • c
  • Related