简体   繁体   中英

C, reading multiple numbers from a single line ignoring the whitespaces

I am working on a problem where I need to input a line of numbers with one or more whitespaces in between and add the numbers. But I am having a problem with ignoring the whitespaces.

I have tried using scanf(" ") and scanf("%*c"). What is the most efficient way to do so?

Thanks.

If the number of input integers in an entered string is unknown then you can use the approach shown in the demonstrative program.

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

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

    while ( fgets( line, N , stdin ) != NULL && line[0] != '\n' && line[0] != '\0' )
    {
        long long int sum = 0;

        const char *s = line;
        char *p = line;

        do
        {
            s = p;
            sum += strtol( s, &p, 10 );
        } while ( s != p );

        printf( "sum = %lld\n", sum );
    }

    return 0;

}

If to enter string

1 2 3 4 5

then the output will be

sum = 15

To read integers, use the format string %d, like this:

#include <stdio.h>

int main(void)
{
    int sum, i, n;

    sum = 0;
    n = scanf("%d", &i);
    while (n == 1) {
        sum += i;
        n = scanf("%d", &i);
    }
    printf("%d\n", sum);
    return 0;
}

If you want to read real numbers, use the format string %lf (which stands for long float) and adjust the code above accordingly.

The way to do it in C++ would be

double a;
double b;
double c;

std::cin >> a >> b >> c;

I am not sure if you can do something very similar in C, please tell me if that was helpful.

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