0

So basically I have to write a program which works with integers ranging from 0 to 10^18 digits long. I was trying to see how can I input such long number in C and then use it. I decided to use unsigned long long int but after using that the program in not accepting input in the String a,and exits.I am unable to understand what is happening inside the code.

#include <stdio.h>
#include <string.h>
int main()
{
   int i,length=0;
   unsigned long long p;
   scanf("%llu",&p);
   printf("%llu\n",p);
   char a[19];
   scanf("%[^\n]s",a);
   length=strlen(a);
   printf("%d\n",length);
   int b[length];
   for(i=0;i<length;i++)
   {    
       b[i]=a[i]-48;
   }
   printf("Input is : ");
   for(i=0;i<length;i++)
   {    
      printf("%d",b[i]);
   }    
   //printf("%d\n",b);
   return 0;
}

The input I gave was 34 then the next lines were:

34
2
Input is : 4816
  • 2
    I'm tolerably sure the problem is that [`scanf()` leaves the newline in the input buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer). After typing the number, you hit return; the next input tries to read some non-newlines, but the first character is a newline, so it fails. You _must_ check the return value from `scanf()` **every** time you use it, without fail. Otherwise, you don't know when things go haywire. You could put a space before the conversion: `" %[^\n]"` (noting that the `s` is a literal character — not part of the scan set `%[…]`). – Jonathan Leffler Mar 17 '18 at 06:58
  • `length=strlen(a);` causes undefined behaviour because `a` is uninitialized (and the scanf failed due to there being no characters matching the scanset) – M.M Mar 17 '18 at 07:02
  • Do you really mean '10^18' digits, or do you mean 'values up to 10^18'? You'll need exabytes of storage to be able to store 10^18 digits; you only need 64-bit numbers to store values up to 10^18. – Jonathan Leffler Mar 17 '18 at 07:02
  • at the first call to `scanf()` entering more than 18 digits will cause the program to crash from a numeric overflow, At the second call to `scanf()`, if the first call was supplied 18 or less digits, then nothing will be input because the newline is still in `stdin` so what ever trash was in the array `b[]` will be used. What happens if the user enters any letter for the second call to `scanf()` etc etc – user3629249 Mar 17 '18 at 07:29
  • Saying "will cause" is over-stating it; "may cause" is valid. It is more likely just to cause weird numbers. – Jonathan Leffler Mar 17 '18 at 08:10
  • Thanks @JonathanLeffler , adding a space before the conversion worked, but I don't understand how? Would you kindly please explain – Priyadarshan Vijay Mar 17 '18 at 10:34

0 Answers0