0
votes

I have this code that work:

 int main()
    {
        char a[100];
        int i;
        int n=3;
        for(i=1;i<=n;i++){
            printf("insert char \n");
            scanf("%c",&a[i]);
            getchar();
        }
        for(i=1;i<=n;i++){
            printf("%c ",a[i]);
        }
    }

I insert a b c he prints a b c, so far so good, I would like to be able to insert the size n with a scanf, but if I put a scanf of n like this:

int main()
        {
            char a[100];
            int i;
            int n;
            scanf("%d",&n);
            for(i=1;i<=n;i++){
                printf("insert char \n");
                scanf("%c",&a[i]);
                getchar();
            }
            for(i=1;i<=n;i++){
                printf("%c ",a[i]);
            }
        }

when I run the program, it causes problems in the second for loop, I enter a b c, and the second for returns empty characters,actually does newline n times,in C when each program finishes "PROCESS RETURNED etc." is printed. When I run the first code the characters are printed on the same line and in the next line there is "PROCESS RETURNED", instead with the second code after the insertion n empty lines are printed and then "PROCESS RETURNED" even if I have not written \ n in the printf. I tried to see if n is stored in the same location as some element of a (with printf ("% p", & a [i]), or printf ("% p", & a) and printf ("% p", & n )), but the address is different. Some idea?

2

2 Answers

2
votes

if first program since you scan chars first , there is nothing in buffer then you call getchar which will take \n as input , but in second program after entering int n you have one \n in buffer(scanf take only one integer and leave \n in buffer) , so when you call scanf for your charecter it will take that \n as input.

so I suggest to add one space in scanf:

 for(i=1;i<=n;i++){
                printf("insert char \n");
                scanf(" %c",&a[i]);//add space here
            }
1
votes

You have to use getchar() after reading n because the newline character '\n' will remain in the input buffer and your second scanf in for loop will read that.

Also you should start with index 0. You can try the following code.

int main()
 {
   char a[100];
   int i;
   int n;
   scanf("%d",&n);
   getchar();
  for(i=0;i<n;i++){
    printf("insert char \n");
    scanf("%c",&a[I]);
    getchar();
  }
  for(i=0;i<n;i++){
   printf("%c ",a[I]);
  }
 }