Sanity Checking in C - c

So I need to sanity check the int n and it must be a number that is higher than zero so I have"
n = strtol(argv[1], &ptr, 10);
if (n <= 0)
{
printf("\nthe number should be a positive integer\n");
return 1;
}
But I also need to make it not accept an input with letters like for example 53e
Can someone help?
I tried isdigit() but I don't really know how to use it properly

Related

Why does my do while statement work this way?

This code works but I'm confused on how. I was writing this program for a class. I needed to only accept positive integers. I created a do...while loop to do so. My question is, why does this code only check the correct way when I have the or "||" in there and not the "&&". I would assume it would need to test both to make sure that it is taking in the correct integers.
#include <stdio.h>
#include <math.h>
main()
{
float i, number, sum=0;
int k;
do
{
printf( "Sumation Calculator\n" );
printf( "Enter number: " );
scanf( "%f", &number );
k = number;
}while(number < 1 || k != number);
while (i <= number)
{
sum = sum + i;
i++;
}
printf( "The summation of %f is %f.\n", number, sum);
return 0;
}
You have two requirements:
That the value be positive
That the value be an integer (no fractional/decimal component)
Your test needs to be true if you need to ask again, not if you have the correct value; testing for the correct value would involve two "positive tests" joined by &&, but you want to test for incorrect values, which means you want to reject if either "negative test" fails. You need to ask again if either condition is violated. If you test number < 1 && k != number that means "I need to ask again only if it's both not positive and non-integer", so 0 (which is not positive, but is an integer) would be accepted, as would 1.5 (which is not an integer, but is positive).
Testing number < 1 || k != number correctly says "I need to ask again if it's not positive or it's not an integer"; if it fails either criterion, you loop and ask again.
Others have explain OP's logic issue.
why does this code only check the correct way when I have the or "||" in there ...
Code is not corrct with only that change. It has too many problems - many of which can be identified by enabling all compiler warnings.
scanf( "%f", &number); will round numeric input text to a float, losing non-integer detection.
k = number; is undefined behavior when number is much outisde int range.
i <= number is bad as i is not yet assigned.
The return value of scanf( "%f", &number ) is not tested for success.
Below is a more robust way to test for input of only positive integers.
I needed to only accept positive integers.
Best to:
Read the line of text into a string.
Parse it as an integer with strtol().
Test for range, etc.
char buf[100];
while (fgets(buf, sizeof buf, stdin)) {
char *endptr;
errno = 0;
long value = strtol(buf, &endptr, 10);
if (buf == endtpr) {
puts("No conversion");
continue;
}
if (errno) {
puts("Out of long range");
continue;
}
if (*endptr != '\n') {
puts("Non-numeric trailing junk");
continue;
}
if (val < 0) {
puts("Only positive values");
continue;
}
// Success, now do something with val
}
This will fail input like "123.0" or "1e2" - which are both whole numbers. Additional code could handle most of those cases.
do
{
...
k = number; // now k == number
} while (number < 1 || k != number);
} while (number < 1 || FALSE);
} while (number < 1);
As you see the condition is not needed.
What is the initial value of i?
By the way it is "Summation" I believe.

How to handle number too big on input in C?

my task is to make a sum of digits of a given number (without knowing its size). All I know is that the number is natural positive (including 0), so 0,1,2,3,4....10^x. The number will be given on stdin, so probably scanf is a solution. I know how I would do the sum, but I dont know how to store (some people suggested not to store) this number because even long long might not be enough if the number is too big.
Please answer more accurate, I'm C beginner. Thanks
If the input number can be arbitrarily large, it is indeed better not to try and convert it as a number but to operate on the digits typed. Note that this method always works anyway:
#include <stdio.h>
int main() {
long sum = 0;
int has_number = 0;
for (;;) {
int c = getchar(); // read the next byte from input
if (c >= '0' && c <= '9') {
sum += c - '0'; // add the digit value
has_number = 1;
} else {
if (has_number) {
printf("sum=%ld\n", sum); // output the current sum and
has_number = 0;
sum = 0; // reset the sum to zero
}
if (c == EOF)
break; // stop at end of file
}
}
return 0;
}
The above program can handle very large numbers, up to at least 200 million digits.

C - Recursive function smaller prime numbers

i got this exercise where it wants me to create a function to check if a number is "Prime", and than create another function to print how many smaller prime numbers are there from the one i checked. The thing is i need to create a recursive function to check the number of smaller prime numbers using the first function(the one that checks if a number is prime or not). This is what i got so far, and i'm stuck here. The recursive function is confusing for me.
#include <stdio.h>
int main() {
int a;
scanf("%d", &a);
checkPrime(a);
smallerPrime(a);
}
int checkPrime (int number) {
if(number % 2 == 0) {
return 1;
} else {
return 0;
}
}
int smallerPrime (int number) {
if(checkPrime(number) % 2 != 0){
return ;
} else {
return ;
}
}
I saw from the comments,that you actually want to check if a number is even,and if so,you want to know how many smaller even numbers there are using recursion,not prime numbers as mentioned in the title,so my answer will refer that.
You could use something like this:
int smallerPrime (int number) {
static int count = -1; // so that the number itself will not be counted
if(number <1) //excluding 0 or negative numbers
return 0;
if(number !=2) {//we know the number has to be even so no check is needed
++count;
smallerPrime(number - 2);
return count+1; // the +1 is in order to count 2 as well
}
else {
return 0;
}
So for example:
Input 10 would give output 4 (8,6,4,2)
As mentioned by paxdiablo,using recursion here is not the best idea.
In case of very big numbers,your program will probably crash.
Furthermore,note that this code works for positive numbers only,as i am not sure if you want to count anything but them(Negative numbers (like -2,-4 and so on) and 0 are also considered even).
I excluded them here.
In main,you need to put the return value of checkPrime in some variable,and use it to determine if you need to use smallerPrime function.
So you should correct that in your code.
Of course,you can do it all in one function with some small changes.

how can i verify that i got N^2 integers from standard input(Stdin)?

I'm having problem with a project in C that i need to submit. i was asked to write a program that gets N and N^2 integers and check whether they create a magic square.
however, i missed that the input should've been from stdin, and i don't know how to do that, as i used printf to request the user to give N and scanned it and then asked a user to enter N^2 integers and to check if it creates magic square. however, i don't know how to do it from stdin.
the input should be of the form: sizeofN,N1,N2,...,N^2. for instance: 3 8 1 6 3 5 7 4 9 2 - will mean that 3 is N and the other elements are what's after it.
so my questions are:
1)how do i obtain values from the standart input(stdin)in the mentioned way? is it from something like while ((c=getchar()) != EOF), or is there a smarter way?
2)how can i check whether i really got N^2 items? (the first number is N and i should get N^2 inputs after it, for instance if i got: 3 8 1 3 4 5 9 8 5 it means that N should be 3 and i should get 9 integers, but i only got 8, how can i write a function that checks that i really got N^2 numbers are getting N?
i already programmed a program to check whether a given matrix forms a magic square, so the question is about receiving information from stdin. please provide code so i can understand and learn.
thank you very much for your kind help.
First get the first number
if( scanf("%d",&N) != 1){
fprintf(stderr,"Error in input");
exit(1);
}
Now you validate whether it is indeed a good number.
if( N <= 0 ){
fprintf(stderr,"Enter integral N >= 1");
exit(1);
}
Now loop over,
for(size_t i = 0; i < N*N; i++){
if( scanf("%d",&a[i]) != 1){
fprintf(stderr,"Enter integral N >= 1");
exit(1);
}
}
In this solution with scanf() you got N^2 numbers because in every iteration you correctly input an integer.
Using getchar() is not a good choice. Because for every magic square of size>=4 will have 2 digits numbers atleast. You can't get them directly using getchar() unless you process them accordingly and make integer numbers out of them which is one option you have with getchar() but unnecessarily complicates thing.
Also in case you want to validate that if there is more number required than entered or to have some more finer control over input taking then you can use fgets() and read a line at once and parse it to int.
If those are provided as arguments to the program then you can easily do the validation part using argc and argv. Suppose you want to check whether the number of input given is alright or not.
So you check,
int main(){
char *ptr;
int N;
errno = 0;
if( argc > 2){
long NN = strtol(argv[1], &ptr, 10);
if (errno != 0 || *p != '\0' || NN > INT_MAX || NN < INT_MAX) {
fprintf(stderr, "%s\n", "Error in parsing");
exit(1);
}
else{
N = (int)NN;
}
}
int totalElmts = N*N;
if( N && totalElmts / N != N){
fprintf(stderr, "%s\n","Overflow");
}
if( argc != (totalElmts + 2) ){
fprintf(stderr, "%s %s %s\n",argv[0],"N","NxN elements");
}
for(size_t i = 2; argv[i] != NULL; i++)
{
//convert argv[i] to `int`
}
...
return 0;
}

C - Counting numbers

I am a coding-beginner and would like to hear your advice relating to following solution of this exercise:
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.
I've written the code below and according to the tests I did, the program fulfills all given tasks. But what do you think about it? How can I improve it?
(And I also think that I am not allowed to use any finished helpful function in any c-library. It is just 'plain' C coding or so. Idk how to describe it.)
(The programming language is C)
#include <stdio.h>
int main(void)
{
long number;
int n=0;
do
{
printf("Enter a number: ");
scanf_s("%ld", &number);
if (number > 0)
{
while (number != 0)
{
number /= 10;
n++;
}
}
else if(number == 0){
n = 1;
}
else {
exit();
}
printf("The number you've entered has %d digits.\n\n",n);
n = 0;
} while (getchar() != 'EOF');
return 0;
}
That getchar it's useless because EOF it's to say that a file it's over and you're not reading an file. Change that to while(number >=0).

Resources