简体   繁体   中英

How to take int and double as input but not a char?

I'm trying to make a while loop that will be used to take an int and a double as input. But sometimes there could be a char in the input which I want to skip, and then continue the loop.

This will skip the loop and I want to still use the scanf:

scanf("%d%lf", &num,&n_double);
while((num != 'a')&&(n_double != 'a'))

Do you mean input validation?

char line[80];
int ival;
double dval;

fgets(line, 80, stdin);

if (sscanf(line, "%d", &ival) == 1)
    /* got an int */
else if (sscanf(line, "%f", &dval) == 1)
    /* got a double */
else
    fprintf(stderr, "Not int nor double\n");

First read the whole line, then use sscanf to parse the input line into an integer and a double. If, however parsing fails to give an int and a double, conclude that as the error case, ie a char present in the line.

You can try this code:

int main(int argc, char const *argv[])
{
    char line[100];
    while(fgets(line, 100, stdin)) {
        int i;
        double d;
        if(sscanf(line, "%d %lf", &i, &d) == 2) {
            printf("%d %lf\n", i, d);
        }
        else {
            printf("wrong input!\n");
        }
    }
    return 0;
}

Edited as per comment:

from cppreference.com

char *fgets( char *str, int count, FILE *stream );

Parameters

str - pointer to an element of a char array

count - maximum number of characters to write (typically the length of str)

stream - file stream to read the data from

Return value

str on success, null pointer on failure.

So, while(fgets(str...)) translates to "while fgets doesn't return null", which translates to "while fgets continues to successfully read the input stream (which in this case is stdin , the standard input)".

Please take a look at the documentation for further clarification.

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