Search code examples
c++asciioutputgetchar

Can anyone please explain this output with a slight modification in the usual getchar_unlocked function()?


I wanted to change the general getchar_unlocked program to print the position of space when the second number is entered.So i introduced 2 more variables r and a, such that r gets incremented every time a non space character is input and a gets r's value when a space character is input. However, by the change i made only the first no. is getting stored in s and a garbage value is getting stored in a. Why so?

   #include <cstdio>
   #define getcx getchar_unlocked
   using namespace std;
   inline void scan( int &n, int &a) //extra parameter a added
  {
    n=0; int r=0;

    char ch;
    ch=getcx();
    while (ch<'0' || ch>'9') //Inclusion of a !=' ' condition 
   {
       if (ch==' ') 
        a=r;
       else
        r++;
      ch=getcx();
   }
   while (ch>='0' &&  ch<='9')
    {
     r++;

     n=10*n + ch -'0';
     ch=getcx();
     }
   }

 int main()
 {

   int t,s,a;
   scan(t,a);
   printf("%d\n",t);

   scan(s,a);
    printf("%d",s); 
   printf("%d",a);
   return 0;
  }

Solution

  • The scan function skips non-digits, then reads 1 or more digits as an integer into n, and finally skips a single non-digit character. In the first loop to skip non-digits, it counts the number of non-spaces read and stores that number into a whenever it sees a space. If it never sees a space, a will remain unmodified.

    So if you give your program an input like 10 20 (with just a single space), that space will be skipped by the first call to scan (the non-digit after the number), and a will never be initialized.

    If you want your scan routine to not skip the character after the number it reads, you need to call ungetc to put it back after reading it and discovering that it is not a digit.