Check for Character instead of Integer [duplicate] - c

This question already has answers here:
Check if a value from scanf is a number?
(2 answers)
Closed 9 years ago.
my program adds numbers entered by the user. It runs and works great until a character is entered instead of an integer. Is there a simple way to make sure only integers are entered from the keyboard?
Here is my code.
#include<stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int n, sum = 0, i, TotalOfNumbers;
printf("Enter the number of integers you want to add\n");
scanf("%d", &n);
printf("Enter %d integers\n",n);
for (i = 1; i <= n; i++)
{
scanf("%d",&TotalOfNumbers);
sum = sum + TotalOfNumbers;
}
printf("Sum of entered integers = %d\n",sum);
return 0;
}

You need to check the return value of scanf. If the input was a valid number, it will return 1. If the input was not a valid number, it will return something else. Here is your code modified to put the checks in.
#include<stdio.h>
#include <stdlib.h>
int get_number()
{
int num;
int ret;
ret = scanf("%d", &num);
if (ret != 1) {
printf("bad number\n");
exit(EXIT_FAILURE);
}
return num;
}
int main(int argc, char **argv)
{
int n, sum = 0, i, TotalOfNumbers;
printf("Enter the number of integers you want to add\n");
n = get_number();
printf("Enter %d integers\n",n);
for (i = 1; i <= n; i++)
{
TotalOfNumbers = get_number();
sum = sum + TotalOfNumbers;
}
printf("Sum of entered integers = %d\n",sum);
return 0;
}

Check the ferror state on the input stream
scanf("%d",&TotalOfNumbers);
if(!ferror(stdin)){
sum = sum + TotalOfNumbers;
}

In addition to posted answer, there options not general as posted, but quicker.
First if you want to skip some final set of characters.In following example all letters,! and + will be skiped
int n;
scanf("%*[a-zA-Z!+]%d",&n);
printf("\n%d",n);
for input
weweqewqQQWWW!!!!+++3332
the output is
3332
Next option is to use buffer wich allowed to read everything untill number is met, and then read the number. The disadvantage is that buffer size is limited
char buf[25];
int n;
scanf("%[^0-9]%d",buf,&n);
printf("\n%d",n);
For input
fgfuf#$#^^#^##4565
Output
4565

Related

Added 0 in output file not visible in console

I am trying to understand why I am having a zero added on to one of my variables userNumberInput. I have been trying to figure out why this is happening for the a bit without a good solution or explanation. It is only happening in the output file, and does not appear to be happening as a result of the variable being set to 0.
For example if you enter 90 the console shows 90, but the output file shows 900.
#include <stdio.h>
#include <stdlib.h>
void Fibonacci (int userInputNumber);
void UserInput (int* userInputNumber);
FILE *fpOut;
int main(int argc, const char * argv[]) {
//Creating global variable for userInput to be passed from function to function
int userInputNumber = 0;
//Opening file for writing output to
if (!(fpOut = fopen("csis.txt", "w"))) {
printf("csis.text could not be opened for output");
exit(1);
}
//Calling two functions and passing appropriate vaiables to each
UserInput(&userInputNumber);
Fibonacci(userInputNumber);
fclose(fpOut);
return 0;
}
void UserInput (int* userInputNumber) {
//Asks the user for a number for the generator
printf("Enter a number into the Fibonacci Generator: ");
scanf("%d", &*userInputNumber);
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);
//While the user continues to enter a negative number it forces the user to enter a new number
while (*userInputNumber < 0) {
printf("Invalid user input, enter a positive number\n\n");
fprintf(fpOut,"Invalid user input, enter a positive number\n\n");
printf("Enter a number into the Fibonacci Generator: ");
scanf("%d", &*userInputNumber);
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);
}
}
void Fibonacci (int userInputNumber) {
//Defines variables used in this function
int firstNumber, secondNumber, i, seriesNumber, length;
firstNumber = 0;
secondNumber = 1;
seriesNumber = 0;
i = 0;
length = 0;
//For loop that adds the two previous number in the series and prints it and then updates the previous numbers
for (i = 0; seriesNumber < userInputNumber; i++) {
if (i <= 1) {
seriesNumber = i;
length++;
} else {
seriesNumber = firstNumber + secondNumber;
firstNumber = secondNumber;
secondNumber = seriesNumber;
length++;
}
//Statement to break the loop when the next number in the series goes above the user input
if (seriesNumber > userInputNumber) {
length -= 1;
break;
}
//Printing the sequence
printf("%d\n",seriesNumber);
fprintf(fpOut,"%d\n",seriesNumber);
}
//Printing the length of the sequence
printf("Length of the sequence: %d", length);
fprintf(fpOut,"Length of the sequence: %d", length);
}
You have to print a newline after printing the value entered, or 0, which is the first term of the sequence, seems to be appended to the input.
Try changing both of the two
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);
to
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d\n", *userInputNumber);

Retaining input values in C?

I have asked for the user to enter in several values to calculate an average, however I'd like to also calculate a gradient which uses the inputted values. How do I name these values so I can use them again? Thank you.
Here is what I have thus far:
#include <stdio.h>
int main () {
int n, i;
float num[1000], total=0, mean;
printf("Enter the amount of x-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d", &n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input x-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean=total/n;
printf("The mean of all the x-values entered is %.2f to 2 decimal places", mean);
{
float num[1000], total=0, mean;
printf("Enter the amount of y-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d",&n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input y-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean = total / n;
printf("The mean of all the y-values entered is %.2f to 2 decimal places", mean);
return 0;
}
}
Naming the variable is really up to you, but `int gradient[NUM_ELEMENTS]; seems appropriate. It is an array, which also seems appropriate if it's purpose is to assist in finding the gradient from a series of numbers.
Steps could be:
1) use printf to ask user for values, specify spaces or commas between values. You can also specify a limit of values. Example printf("enter 5 numbers separated by commas\n:");
2) use scanf or similar to read values from standard input (the terminal) into the array: scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
3) use the array an a function that will compute the gradient.
Simple example:
(where gradient computation, error checking, bounds checking etc. is all left to you)
int get_gradient(int a[5]);
int main(void) {
int gradient[5];
int iGradient=0;
printf("enter 5 numbers separated by commas");
scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
iGradient = get_gradient(gradient);
return 0;
}
int get_gradient(int a[5])
{
return [do computation here using array a];
}
Edit:
The above example works only if you know the number of elements at compile time. It uses an int array that has been created on the stack. If you do not know how big of an array you will need until run-time, for example if user input determines the size, then the array size needs to be determined at run-time. One options is to create the variable needed on the heap. (read about stack and heap here) The following uses some techniques different from the simpler version above to get user input, including a function I called get_int(), which uses scanf() in conjunction with strtol(). Here's the example:
int main(void) {
char input[80]={0};
char **dummy={0};
long *gradient = {0};
int iGradient=0;
int arraysize;
int i;
char* fmt = "%[^\n]%*c";
printf("how many numbers will be entered?");
scanf(fmt, input);
arraysize = strtol(input, dummy, 10);
gradient = calloc(arraysize, sizeof(long));
if(gradient)
{
for(i=0;i<arraysize;i++)
{
gradient[i] = get_int();
}
iGradient = get_gradient(gradient, arraysize);
//free gradient when done getting result
free(gradient);
}
return 0;
}
int get_gradient(int *a, int num)
{
int grad = 0, i;
//do something here to compute gradient
return grad;
}
long get_int(void)
{
char input[80]={0};
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}

Specific digit count in an integer in C

For example: if user input is 11234517 and wants to see the number of 1's in this input, output will be "number of 1's is 3. i hope you understand what i mean.
i am only able to count number of digits in an integer.
#include <stdio.h>
int main()
{
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0)
{
n/=10;
count++;
}
printf("Digits in your number: %d",count);
return 0;
}
maybe arrays are the solution. Any help would be appreciated. thank you!
You don't need array. Try something like this:
int countDigits(int number, int digitToCount)
{
// Store how many times given number occured
int counter = 0;
while(number != 0)
{
int tempDigit = number % 10;
if(tempDigit == digitToCount)
counter++;
number = number/10;
}
return counter;
}
So, you've already found that you can convert 1234 to 123 (that is, remove the least significant digit) by using number / 10.
If we wanted to acquire the least significant digit, we could use number % 10. For 1234, that would have the value of 4.
Understanding this, we can then modify your code to take this into account:
int main() {
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0) {
if (n % 10 == 1)
count++;
n /= 10;
}
printf("Number of 1s in your number: %d", count);
return 0;
}
You may want to use convert your int to a string like this :
char str[100];
sprintf(str, "%d", n);
Then, you can just iterate on str in order to find the occurrences of your digit.

C program on part of algorithm which focus on finding Armstrong-like number

I have a problem with C program. The idea of it is similar to Armstrong number checking. Say if the input number is 123. Program needs to check if condition, for example 123=1^1+2^2+3^3 is true. I know how to add digits,but have a problem with powers. It is obvious that I need a loop for powers from 1 to the number of digits. In Armstrong number algorithm you have similar power on every digit. For example 153=1^3+5^3+3^3. Here is what I have so far:
#include<stdio.h>
int main()
{
int n,d,s=0,o,i,k;
printf("n=");scanf("%d",&n);
d=n;
while(d!=0)
{
o=d%10;
s=s+o;
d=d/10;
k++
}
printf("sum:%d",s);
printf("number of digits:%d",k);
return 0;
}
Thanks for the answers.
You need first get the lenth of number, which is used to determine how many times you need to get into loop to calculate each bit.
For example, number 123, you first need to know the number is 3 bits len, then you can mutilply number 3 three times, number 2 twice, and number 1 once.
I use a temporary string to achieve this
here is codeļ¼Œ a little bit alteration on yours
#include <stdio.h>
#include <string.h>
#define MAX_NUM_LEN 16
int main()
{
char tmp_num[MAX_NUM_LEN] = {0};
int len,n,d,s=0,o,i,tmp_len, tmp_o;
printf("n=");scanf("%d",&n);
sprintf(tmp_num, "%d", n);
len = strlen(tmp_num);
tmp_len = len;
d=n;
while(d!=0)
{
o=d%10;
for (tmp_o = 1, i = tmp_len; i > 0; i--)
tmp_o *= o;
s=s+tmp_o;
d=d/10;
tmp_len--;
}
printf("sum:%d\n",s);
printf("number of digits:%d\n",len);
return 0;
}
results:
According of what I've understood I think this is what the OP is looking for:
int power(int base, int exp)
{
if (base == 0) return 0;
int result=1;
while (exp-- > 0) result*=base;
return result;
}
void calculate(int number)
{
int d=number;
int tmpnumber=number;
int n=0;
while (d > 0)
{
n++;
d /=10;
}
printf("Number of digits: %d\n", n);
int k=0;
int sum=0;
while (n--)
{
// get digits from left to right
d=number / power(10, n);
k++;
sum+=power(d, k);
number %= power(10, n);
printf("%d^%d=%d\n", d, k, power(d, k));
}
printf("\n%5d %5d", tmpnumber, sum);
}
int main(int argc,char *argv[])
{
int value;
while (TRUE)
{
printf("Enter value (0 = Quit): ");
scanf("%d", &value);
if (value <= 0) return 0;
calculate(value);
printf("\n");
}
}

Finding biggest and smallest numbers using user input

Well it is a problem about finding the biggest and smallest number in a group of numbers, but we do not know how many numbers the user wants-
So far this is what i have done:
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
int i;
int maxi=0;
int minim=0;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf ("%d", &num);
while (num>0)
{
printf ("\nEnter number:");
scanf ("%d", &i);
if (num>i)
minim=i++;
else
if (i>num)
max=i++;
cont++;
}
printf ("\nBiggest number is es: %d", maxi);
printf ("\nSmallest number is: %d", minim);
getch();
return 0;
}
I did my program to ask how many numbers the user will want to put and i made the program to read them, BUT when it reads the biggest or/and smallest numbers it will sometimes changes biggest with small and it will not read negative numbers.
How do i do to make my program better?
You're comparing against the wrong values.
do
{
printf("Enter a number.\n");
scanf("%i", &input);
if min > input
min = input
if max < input
max = input
} while (input > 0);
#include <stdio.h>
#include <conio.h>
#include <limits.h>
int main(){
int num;
int i;
int maxi=0;
int minim=INT_MAX;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf("%d", &num);
if(num > 0){
while (num>0){
printf ("\nEnter number:");
if(scanf("%d", &i) == 1 && !(i<0)){
if(minim > i)
minim = i;
if (maxi < i)
maxi = i;
++cont;
--num;
} else {
//fprintf(stderr, "redo input!\n")
;
}
scanf("%*[^\n]%*c");
}
printf ("\nBiggest number is : %d", maxi);
printf ("\nSmallest number is : %d\n", minim);
}
getch();
return 0;
}
You should initialize mini to the largest possible int, i.e. INT_MAX and maxi to the smallest possible int, i.e., INT_MIN. This way, even if the first number is negative, it will be considered for maxi, and if the first number is positive it will still be considered for mini. The constants INT_MAX and INT_MIN are included in <climits> or <limits.h>.
Also, you are comparing the current entered number with num, which is the counter of numbers entered by user, not one of the values he wants to compare. A better modified code would be :
#include<limits.h>
#include<stdio.h>
int main()
{
int num;
int maxi=INT_MIN; //initialize max value
int mini=INT_MAX; //initialize min value
int temp;
scanf("%d", &num); //take in number of numbers
while(num--) //loop "num" times, num decrements once each iteration of loop
{
scanf("%d", &temp); //Take in new number
if(temp>maxi) //see if it is new maximum
maxi=temp; //set to new maximum
if(temp<mini) //see if new minimum
mini=temp; //set to new minimum
}
printf("\nMaxi is:\t%d\nMini is:\t%d\n", maxi, mini); //print answer
return 0;
}

Resources