Chase
Chase

Reputation: 5615

How can I take integer input dynamically and have the loop terminate on pressing enter?

I need to take integer input dynamically and have it terminated as soon as user pressed enter. I never had any problem with this when I'm taking chars as input as I can easily check for newlines and each char is a single character. But here, I can't just take a char input and substract it by '0' as when I enter 10, the char value is 1 and then 0.

Here is a piece of the code I'm using :

int no;
while (scanf_s(" %d", &no) == 1)
    {
        printf("%d ", no);
    }

And here's another piece of code that I use for inputting chars, this works fine for single digit integers too :

char no;
while ((no=getchar()) != EOF && no != '\n')
    {
        printf(" %d ", no - '0');
    }

The scanf loop doesn't terminate when pressing enter but it does take the inputs all correctly. Whereas, the getchar loop terminates correctly but only stores 1 digit integers.

How can I have integer inputs be terminated at blank line user input?

Upvotes: 1

Views: 362

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

You can use standard function fgets to read the input into a character array and then extract numbers using standard function strtol.

Here is a demonstrative program

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int is_empty( const char *s )
{
    return s[strspn( s, " \t" )] == '\n';   
}

int main(void) 
{
    enum { N = 100 };
    char line[N];

    while ( fgets( line, N, stdin ) && !is_empty( line ) )
    {
        char *endptr;

        for ( const char *p = line; *p != '\n'; p = endptr )
        {
            int num = strtol( p, &endptr, 10 );
            printf( "%d ", num );

        }
    }

    return 0;
}

If to input the following lines

1
2 3
4 5 6
7 8
9

(the last line is empty that is the user just pressed Enter)

then the output will look like

1 2 3 4 5 6 7 8 9

Upvotes: 2

Related Questions