0

My program contains input code for character , but during debugging its not considering it.

It considers input for other datatypes(int,float,etc)

program:

               #include<stdio.h>
               int main()
                 {
                    int n,i=0;
                    char c;                               
                    scanf("%d",&n);
                    int a[20];
                    while(1)
                        {
                           scanf("%c",&c);
                           if(c=='\n')
                           break;
                           else
                             {
                                if(c!=32)
                                a[i++]=c-48;
                             }

                        }
                   for(i=0;i<10;i++)
                   printf("%d ",a[i]);

                    return 0;
               }

debugging screen: enter image description here

8
  • 1
    I suggest scanf("%c",&c); should be scanf(" %c",&c); with an added space to clear off leading whitespace. Please see scanf() leaves the newline char in buffer? Most format specifiers like %d and %f filter out that leading whitespace but %c does not, unless you instruct it with the space. Commented May 15, 2018 at 19:52
  • Aside: c-48 suggests there is ASCII coding and you want to extract a digit, in which case c - '0' is both clear and portable. Commented May 15, 2018 at 19:53
  • @user3121023 yes but that might mess with several characters entered on one line, maybe with more than one space separating. The " %c" is clean and reliable. Commented May 15, 2018 at 19:59
  • @user3121023 I don't understand your concept of "breaking on a newline". Data for scanf can be entered all on one line. I suggest using fgets, as ever, if you want an emtpy line to stop the input. Commented May 15, 2018 at 20:07
  • 1
    @user3121023 I see, the first %c entry will pick up the newline after the %d entry before the loop. Commented May 15, 2018 at 20:10

1 Answer 1

1

Your scanf("%d",...) leaves a new line character in the buffer, which is then immediately consumed by the subsequent scanf("%c",...). To overcome this, let only one scanf after the scanf("%d",...) consume white spaces:

int main()
{
    int n,i=0;
    scanf("%d",&n);

    int a[20];
    char c=0;
    scanf(" %c",&c);  // Consume white spaces including new line character before the value for c.
    while(c!='\n' && i < 20)
    {
        if(c!=32) {
            a[i++]=c-'0';
        }
        scanf("%c",&c);
    }
    for(int x=0;x<i;x++)
        printf("%d ",a[x]);

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.