How can scanf work before its previous line?

In the following code, when I enter anything in [a-z] followed by \n for c, it accepts and prints 'enter d'. But when I give any numbers for c, that value is scanned for variable d and then then only 'enter d' displayed. How does this happen?

#include<stdio.h>

void main()
{
    char c[10],d[10];
    int i,j;

    printf("enter c:");
    i=scanf("%[a-z]%1[\n]",c);

    printf("\nenter d:");
    j=scanf("%[ 0-9]%1[\n]",d);

    printf("\nc : %s-%d\n",c,i);
    printf("\nd : %s-%d\n",d,j);
 }

My output is:

enter c:12

enter d:c:�-0

d:12-2

Upvotes: 1

Views: 272

Answers (2)

Vishwadeep Singh
Vishwadeep Singh

Reputation: 1043

Try this:

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

int main()
{
    char *c = malloc(10);
    char *d = malloc(10);

    int i = 0;

    printf("enter c:");
    int x = EOF;
    while (( x = getchar()) != '\n' && x != EOF) {
        if (i >= 10) {
            break;
        }
        if (x >= 97 && x <= 122) {
            c[i++]=(char)x;
        }
    }
    printf("\nenter d:");
    x = EOF;
    i = 0;
    while (( x = getchar()) != '\n' && x != EOF) {
        if (i >= 10) {
            break;
        }
        if (x >= 48 && x <= 57) {
            d[i++]=(char)x;
        }
    }
    printf("\nc : %s\n",c);
    printf("\nd : %s\n",d);
    return 1;
 }

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409472

If you want to skip over whitespace, like the ending newline, then add a leading space before the format code:

printf("enter c: ");
i = scanf(" %s", c);

printf("enter c: ");
j = scanf(" %s", d);

This will make scanf skip all whitespace.

Also, if you want to read a number, why not read it as a number using e.g. the "%d" format code? If you want it as a string, then use e.g. snprintf to convert it after scanning.

Upvotes: 2

Related Questions