Raman Singh
Raman Singh

Reputation: 329

Ignoring everything other than integers scanf

I would like to take an array of integers as an input . Even if some one enter a space or an alpahabet, I want to ignore it.

int i=0;
while(L--){
    scanf("%d",&arr[i++]);
}

But if I enter: 4 wtf the arr[0] gets initialized to 4 and the loop ends. Is there a way I can ignore everything after a space in scanf and just take the integers. The input can be of form: 4 abc 3 def 7 ghi.

Upvotes: 2

Views: 3326

Answers (4)

jwaliszko
jwaliszko

Reputation: 17064

I think that what you'd actually like to achieve here is to extract all numbers from a random input. I propose to use fgets to read the input into a buffer and next, using isdigit and strtol, extract the numbers:

#include <stdio.h>

int main(void)
{
    char buff[255] = {0};
    fgets(buff, sizeof(buff), stdin); // read data from stdin
    char *ptr = buff;

    do {
        if(!isdigit(*ptr)) // check if current character is a digit 
            continue; // if not...
        long val = strtol(ptr, &ptr, 10); // read a number
        printf("%ld\n", val); // print it   
    } while(*ptr++); // ...move to next character
}

...and the quick test:

[root@dmudms01 temp]# ./a.out 
1abc23 **4
1
23
4

Upvotes: 1

Jayesh Bhoi
Jayesh Bhoi

Reputation: 25865

I think like this?

int a;
scanf("%d %*s", &a);
printf("%d\n",a);

And

input: 11 wwwww

output: 11

The * is used to skip an input without putting it in any variable.

Upvotes: 1

0xF1
0xF1

Reputation: 6116

You can use fgets to get the input string from stdin and then use sscanf to filter out integer from input string.

char input[50];
int num;
fgets(input, 50, stdin);

sscanf(input, "%d %*s", &num);

The %*s rejects the string after the integer encountered.

Upvotes: 1

haccks
haccks

Reputation: 106012

Try this

while(L--){
    scanf("%d",&arr[i++]);
    while(getchar() != '\n'); // Consumes all characters after space.
}

Upvotes: 1

Related Questions