Write a program that loops prompting for positive or zero integers of data type long. Then the number of digits the integer consists of (in decimal representation) should be printed to stdout. Entering a negative number immediately stops the program. Output examples: 0 has 1 digit. 999 has 3 digits. etc.
(And I think that I am not allowed to use any finished helpful function in any C library. It is just 'plain' C coding or so. I don't know how to describe it. We haven't learned arrays, strings etc. yet)
I heard the tips and have already adjusted it in the code below, so this is v2.
Questions:
I found two solutions yet to get this exercise/program 'working'. You can see it in v2 and v3, I've posted below.
I use VS 2017, i.e. when I 'Start without debugging' (CTRL+F5), then the CMD will be closed immediately, but when I go to Project-Properties/Linker/System and choose "Console (/SUBSYSTEM:CONSOLE) at SubSystem, the CMD-window stays.
Now the comparison between v2 and v3:
I.e. when I use v2 I do not need to set a specific "SubSystem" as I told you before. I think it is because of getchar()
in the while()
is waiting for an input.
But I can also a while without 'EOF', which some guys on SO suggested before, so I made v3 that uses the while without getchar()
. But to see my program, I have to set a "SubSystem" as I described before.
What solution is 'better'? And what would you improve?
Here is my C code v2:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
long number = 0;
int n = 0;
int i = 0;
do
{
printf("Enter a number: ");
fflush(stdout);
i = scanf_s("%ld", &number);
if(i == 1)
{
if (number < 0)
{
exit(EXIT_FAILURE);
}
else if (number == 0)
{
n = 1;
}
else
{
while (number != 0)
{
number /= 10;
n++;
}
}
}
else
{
printf("Error - You've probably entered nothing."); //Idk what to write here, because the return-value of scanf_s can be less then 1 in this case so it must be zero,
} //if nothing is entered and somehow the program makes it into this else.
printf("The number you've entered has %d digits.\n\n", n);
n = 0;
} while (getchar() != 'EOF');
return 0;
}
Here is my C-Code v3:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
long number = 0;
int n = 0;
int i = 0;
int buffer = 0;
do
{
printf("Enter a number: ");
fflush(stdout);
i = scanf_s("%ld", &number);
buffer = number;
if(i == 1)
{
if (number < 0)
{
exit(EXIT_FAILURE);
}
else if (number == 0)
{
n = 1;
}
else
{
while (number != 0)
{
number /= 10;
n++;
}
}
}
else
{
printf("Error - You've probably entered nothing."); //Idk what to write here, because the return-value of scanf_s can be less then 1 in this case so it must be zero,
} //if nothing is entered and somehow the program makes it into this else.
printf("The number you've entered has %d digits.\n\n", n);
n = 0;
} while (buffer >= 0);
return 0;
}
while (getchar() != 'EOF');
probably doesn't do what you think it does. Multicharacter constants aren't what you want there. \$\endgroup\$