carraysscanfdo-whilenull-character

Using scanf for character input, but the do-while loop wont stop at the null character


I'm completely new to programming (1st term in uni) and I can't keep up with my lecturer. At the moment I'm stuck on this exercise (for much more time than I'm willing to admit). I've tried to find help on the internet (in this site and others as well), but I can't, since our lecturer has us use a very simple form of c. I'm not asking necessarily for a complete answer. I'd really appreaciate even some hints about where I'm on the wrong. I understand that it might be really simple for some, that the question might seem ignorant or stupid and I feel bad for not getting what's wrong, but I need to try to understand.

So, what I'm trying to do is use scanf and a do while loop so the user can input characters in an array. But I don't understand why the loop won't stop when the user presses ENTER. There's more to the code, but I'm trying to take it slowly, step by step. (I'm not allowed to use pointers and getchar etc).

#include <stdio.h>
main()
{
      char a[50];
      int i;

      printf("Give max 50 characters\n");

      i=0;

      do
      {
            scanf("%c", &a[i]);
            i=i+1;
      }
      while((i<=50) && (a[i-1]!='\0'));

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

Solution

  • There aren't any nul-terminated strings here, but only string arrays.

    So, when pressing enter, a[i-1] is \n not \0 (scanf with %c as parameter doesn't nul-terminate the strings, and ENTER is just a non-nul character with code 10 AKA \n)

    Then don't print the rest of the string because you'll get junk, just reuse i when printing the string back:

    #include <stdio.h>
    main()
    {
          char a[50];
          int i;
    
          printf("Give max 50 characters\n");
    
          i=0;
    
          do
          {
                scanf("%c", &a[i]);
                i=i+1;
          }
          while((i<sizeof(a)) && (a[i-1]!='\n'));  // \n not \0
          int j;
          for(j=0; j<i; j++)  // stop at i
                printf("%c", a[j]);  // output is flushed when \n is printed
     }
    

    Also test with i<50 not i<=50 because a[50] is outside the array bounds (I've generalized to sizeof(a))