Scanf for digits - c

I am pretty new in C and I have a question about scanf just for digits. What I need to do is scanf in input just 3 digits, antoher characters or symbols should be evaluate as trash. Or maybe I need use isdigit() but I am not sure how it works. I have just that, but I know that it doesn't work:
scanf("%d, %d, %d", &z, &x, &y);

You could read a string, use a scan set to filter it and convert it to an integer.
See scanf: http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char num1[256], num2[256], num3[256];
scanf("%s %s %s", num1, num2, num3);
sscanf(num1, num2, num3, "%[0-9]d %[0-9]d %[0-9]d", num1, num2, num3);
int n1 = atoi(num1), n2 = atoi(num2), n3 = atoi(num3); // convert the strings to int
printf("\n%d %d %d\n", n1, n2, n3);
return 0;
}
Sample Input & Output:
2332jbjjjh 7ssd 100
2332 7 100

A little more complicated solution, but prevents overflow of array and works for any kind of input. get_numbers_from_input function takes array where read numbers will be put and maximum count of numbers in array and returns count of numbers read from standard input. function reads characters from standard input until enter is pressed.
#include <stdio.h>
//return number readed from standard input
//numbers are populated into numbers array
int get_numbers_from_input(int numbers[], int maxNumbers) {
int count = -1;
char c = 0;
char digitFound = 0;
while ((c = getc(stdin)) != '\n') {
if (c >= '0' && c <= '9') {
if (!digitFound) {
if (count == maxNumbers) {
break; //prevent overflow!
}
numbers[++count] = (c - '0');
digitFound = 1;
}
else {
numbers[count] = numbers[count] * 10 + (c - '0');
}
}
else if (digitFound) {
digitFound = 0;
}
}
return count + 1; //because count starts from -1
}
int main(int argc, char* argv[])
{
int numbers[100]; //max 100 numbers!
int numbersCount = get_numbers_from_input(numbers, 100);
//output all numbers from input
for (int c = 0; c < numbersCount; ++c) {
printf("%d ", numbers[c]);
}
return 0;
}

Try this.
If the first char is not a digit.
Use "%*[^0-9]" to skip chars which is not digits.
' * ' is an optional starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument), and ' ^ ' means any number of characters none of them specified as characters between the brackets.
#include <stdio.h>
int main()
{
int x,y,z;
if(!scanf("%d",&x)==1) scanf("%*[^0-9] %d",&x);
if(!scanf("%d",&y)==1) scanf("%*[^0-9] %d",&y);
if(!scanf("%d",&z)==1) scanf("%*[^0-9] %d",&z);
printf("%d %d %d\n",x,y,z);
return 0;
}
Input & Output
fehwih 2738 #$!(#)12[3]
2738 12 3
Reference from: http://www.cplusplus.com/reference/cstdio/scanf/

Related

Comparing digits of two inputs to see if they are the same

I am currently trying to finish a code where a user inputs two 5 digit long numbers. The code then checks to see if there are any identical numbers in the same spot for the two numbers and displays how many identical numbers there are in the same spot of the two inputs. (ex. comparing 56789 and 94712 there would be one similar digit, the 7 in the 3rd digit place.) As of now I have been able to break down the inputs into the digits in each spot, I just need help comparing them. Originally I thought I could just create an int that would serve as a counter and use modulus or division to output a 1 whenever the digits were the same, but I have been unable to put together a formula that outputs a 1 or 0 depending on if the digits are alike or not.
suppose you know the length of strings n (as a condition you would need them to be equal, if they differ in length other validation is needed)
//n is the length of string
for(int i=0;i<n;i++)
{
if(string1[i]==string2[i])
{
//do something, make a counter that increments here...
//also save index i, so you can tell the position when a match occured
}else
{
//do something else if you need to do something when chars didnt match
}
}
Here you when i=0, you are comparing string1[0] with string2[0], when i=1, you compare string1[1] with string2[1] and so on.....
I'd recommend reading the two in as strings or converting to strings if you have the ability to. From there it's a simple string compare with a counter. Something like this:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int is_numeric(char *str)
{
while (*str)
if (!isdigit(*str++))
return (0);
return (1);
}
int main(void)
{
char num1[32];
char num2[32];
int count = 0;
printf("Digit 1\n>> ");
if (scanf("%5s", num1) != 1 || !is_numeric(num1))
return (0);
printf("Digit 2\n>> ");
if (scanf("%5s", num2) != 1 || !is_numeric(num2))
return (0);
if (strlen(num1) != 5 || strlen(num2) != 5)
return (0);
for (int i=0; i<5; ++i)
if (num1[i] == num2[i])
++count;
printf("%d\n", count);
return (0);
}
You can do it very easy using modulo (%) and divide (/). First you do % 10 to get the least significant digit and do the compare. Then you do / 10 to remove the least significant digit. Like:
#include <stdio.h>
#include <string.h>
int main(void) {
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1 || i1 < 10000 || i1 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1 || i2 < 10000 || i2 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
for (i=0; i<5; ++i)
{
if ((i1 % 10) == (i2 % 10)) ++cnt; // Compare the digits
i1 = i1 / 10;
i2 = i2 / 10;
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
It can also be done using strings. Read the input as unsigned int and then convert the value to a string using snprintf and finally compare the two strings character by character.
Something like:
#include <stdio.h>
#include <string.h>
int main(void) {
char str1[32];
char str2[32];
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str1, 32, "%u", i1);
if (strlen(str1) != 5) // Convert to string
{
printf("input error - not 5 digits\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str2, 32, "%u", i2); // Convert to string
if (strlen(str2) != 5)
{
printf("input error - not 5 digits\n");
return 0;
}
for (i=0; i<5; ++i)
{
if (str1[i] == str2[i]) ++cnt; // Compare the characters
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
The reason for taking the input into a unsigned int instead of directly to a string is that by doing that I don't have to check that the string are actually valid numbers (e.g. the user type 12W34). scanf did that for me.

Using Array Integer

I'm new in C programming language.
I need to get every digit separately that user have entered.
Here is my code:
#include <stdio.h>
int main()
{
int n[100];
printf("Enter a number: ");
scanf("%d",&n);
printf("%d %d %d",n[1],n[2],n[3]);
return 0;
} //i know that my code is not assigning like i want.
and now for example user entered a number like 123, i want the output like 1 2 3, How can i assign every digit to n[i] ? Without using string to int or int to string like atoi? Here is what Im going to do: User will enter a number and the program will search from Matrix 100x100 in row or column. i think i need to get the every digit separately to search.
No need to go to character array. The lats digit of a number n can be computed using n%10. Then you can remove the last digit using n /= 10. So this cycle would print the digits in reverse order:
void print_rev_digits(int n) {
while (n) {
printf("%d\n", n%10);
n /= 10;
}
}
And using a stack you can print the digits in the correct order. You can also use recursion for this(which will use stack for you). I am deliberately not posting a complete solution.
In this case you should read the user input character by character:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main()
{
char input[100];
int n[100];
printf("Enter a number: ");
if (fgets(input, sizeof(input), stdin)) { // attempt to read a line
int i;
for (i = 0; input[i]; i++) { // for each entered character
if (input[i] >= '0' && input[i] <= '9') { // is a digit
n[i] = input[i] - '0';
printf("%d ", input[i] - '0');
}
else if (isspace(input[i])) // end of entered integer
break;
else {
printf(stderr, "Input is not a number\n");
return -1;
}
}
printf("\n");
} else {
fprintf(stderr, "User did not enter valid input.\n");
}
return 0;
}

Input several numbers from array and each one number check for integer or not

everyone!
I hope someone can help me figure out something in C language.
This is my first seriously homework in IT, I have no experience and I'm learning in e-studies, so teacher help isn't very available.
I need to develop console application in C language. User need to input 10 integer numbers, if insert number isn't integer, need to output error and again re-enter new number until all 10 integer numbers will be inserted.
Everything works in case if I say that these 10 numbers can't be 0 (I make this to be sure that my if-else statement working), but won't work when I want that every input number will be check if it is integer or not.
How can I do it right.
Please help
so far my code look like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
float f;
int numbers[10];
for (i = 0; i < 10; i++)
{
scanf ("%d", &numbers[i]);
if (numbers[i] != 0)
{
scanf ("*%d", &numbers[i]);
}
else
{
printf ("\nError!Entered number is't integer \n");
printf ("\nPlease insert number again \n");
scanf("%*d", &numbers[i]);
}
}
}
#include <stdio.h>
int main(void) {
int i = 0;
int val;
char ch;
int numbers[10];
while(i < 10) {
val = scanf("%d", numbers + i); // read the integer into a[i]
if(val != 1) {
while((ch = getchar()) != '\n') // discard the invalid input
; // the null statement
printf("Error! Entered number is not an integer.\n");
printf("Please enter an integer again.\n");
val = scanf("%d", numbers + i);
continue;
}
++i;
}
// process the numbers array
return 0;
}
I write this line again
val = scanf("%d", numbers + i);
Now it works how I need. Great - thanks a lot
There are several techniques you might use:
Read the number as a string and reject if it contains characters not suitable for an integer. The use sscanf() to convert the string to integer.
Read the number as a float and reject if it is out of integer range or it has a non-integer value.
Read the input character by character and build up an integer value. If invalid characters appear, reject the value.
scanf returns the number of input items successfully matched and assigned. You can check this value for 1 for each call of scanf. If the value is 0, then you should discard the input to clear the stdin buffer and read input again.
#include <stdio.h>
#include <ctype.h>
int main(void) {
int i = 0;
int val;
char ch;
int numbers[10];
while(i < 10) {
// read an integer and the first non-numeric character
val = scanf("%d%c", numbers + i, &ch);
// if the number of items assigned by scanf is not 2 or if
// the first non-numeric character is not a whitespace, then
// discard the input and call read input again.
// for example input of type 32ws are completely discarded
if(val != 2 || !isspace(ch)) {
while((ch = getchar()) != '\n') // discard the invalid input
; // the null statement
printf("Error! Entered number is not an integer.\n");
printf("Please enter an integer again.\n");
continue;
}
++i;
}
// process the numbers array
return 0;
}
Although I am not entirely clear on the details of your question, here is an outline of code similar to what you want:
int main(void)
{
int i;
int numbers[10];
int sum = 0;
for(i=0; i<10; ++i)
{
printf("Enter #%d:\n", i+1);
scanf("%d", numbers+i);
if (numbers[i] % 2 == 0) // Then Number is even
{
sum += numbers[i];
}
}
printf("The sum of only the even numbers is %d\n", sum);
getch();
return 0;
}
To read an int, suggest fgets() then sscanf() or strtol()
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i;
int numbers[10];
for (i = 0; i < 10; ) {
char buffer[50];
if (fgets(buffer, sizeof buffer, stdin) == NULL) break;
int n; // number of `char` parsed
if (sscanf(buffer, "%d %n", &numbers[i], &n) != 1 || buffer[n] != '\0') {
printf("Error! Entered number is not an integer.\n");
printf("Please enter an integer again.\n");
continue;
}
i++;
}
return 0;
}
The strtol() approach. This detects overflow issues:
if (fgets(buffer, sizeof buffer, stdin) == NULL) break;
char *endptr;
errno = 0;
long num = strtol(buffer, &endptr, 10);
if (errno || num < INT_MIN || num > INT_MAX) Handle_RangeError();
if (buffer == endptr || *endptr != '\n') Handle_SyntaxError();
numbers[i] = (int) num;
Recommend making a int GetInt(const char *prompt) function that can be used repeatedly.
User input is evil. Do not trust it until well vetted.

How to test input is sane

Consider the following simple C program.
//C test
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d",&a,&b);
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
How do you check the values entered are actually two integers in some sensible range? Currently, if you just enter "a" and then return you get the output "Sum of entered numbers = 32767".
Examples of incorrect input I would like to prevent.
2 3 4 (wrong number of numbers)
apple (not a number)
11111111111111111111111111 1111111111111111111111111111111111111 (numbers out of range)
Or should I be using fgets and sscanf or even strtol ?
User input is evil. Parse per:
(optional whitespace)[decimal int][whitespace][decimal int](optional whitespace)
strtol() and family have better error handling than scanf().
Coda: Best to handle user input in a helper function. Break into 2 parts: I/O and parsing.
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// return 1 (success), -1 (EOF/IOError) or 0 (conversion failure)
int Readint(const char *prompt, int *dest, size_t n) {
char buf[n * 21 * 2]; // big enough for `n` 64-bit int and then 2x
fputs(prompt, stdout); // do not use printf here to avoid UB
fflush(stdout); // per #OP suggestion
if (fgets(buf, sizeof buf, stdin) == NULL) {
return -1;
}
const char *p = buf;
while (n-- > 0) {
char *endptr;
errno = 0;
long l = strtol(p, &endptr, 10);
if (errno || (p == endptr) || (l < INT_MIN) || (l > INT_MAX)) {
return 0;
}
*dest++ = (int) l;
p = endptr;
}
// Trailing whitespace OK
while (isspace((unsigned char) *p)) p++;
// Still more text
if (*p) return 0;
return 1;
}
int main() { // for testing
int Result;
do {
int dest[2] = { -1 };
Result = Readint("Enter two numbers to add\n", dest, 2);
printf("%d %d %d\n", Result, dest[0], dest[1]);
} while (Result >= 0);
return 0;
}
You can use like:
if( scanf("%d%d",&a,&b) == 2)
{
//two integer values has been read successfully
//do your stuff here
}
else
{
//Wrong input
}
Also you can do this to prevent anything after second number
int a,b;
char c;
if( scanf("%d%d%c", &a, &b, &c) == 3) {
if (c == '\n') {
puts("good");
}
} else {
puts("bad");
}
return 0;
}
You can use the following macro
#define SCAN_ONEENTRY_WITHCHECK(FORM,X,COND) \
do {\
char tmp;\
while(((scanf(" "FORM"%c",X,&tmp)!=2 || !isspace(tmp)) && !scanf("%*[^\n]"))\
|| !(COND)) {\
printf("Invalid input, please enter again: ");\
}\
} while(0)
and you call it in this way in the main
int main()
{
int a, b, c;
printf("Input first integer, valid choice between 0 and 10: ");
SCAN_ONEENTRY_WITHCHECK("%d",&a,(a>=0 && a<=10));
printf("Input second integer, valid choice between 0 and 10: ");
SCAN_ONEENTRY_WITHCHECK("%d",&b,(b>=0 && b<=10));
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
for more detail concerning this macro please refer to: Common macro to read input data and check its validity
A simple way would be,
int a=0, b=0, c=0;
initialise them to 0
Additionally, the check suggested by Midhun is good to check if there are two inputs.
you can test this one.
#include <stdio.h>
int main(void)
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d",&a,&b);
if(scanf("%d%d",&a,&b) == 2)
{
c = a + b;
printf("Sum of entered numbers = %d\n",c);
}
return 0;
}

How to read numbers separated by space using scanf

I want to read numbers(integer type) separated by spaces using scanf() function.
I have read the following:
C, reading multiple numbers from single input line (scanf?)
how to read scanf with spaces
It doesn't help me much.
How can I read numbers with space as delimiter. For e.g. I have following numbers as input 2 5 7 4 3 8 18 now I want to store these in different variables.
Please help.
I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.
scanf("%d %d %d", &var1, &var2, &var3);
Similarly if you want to read comma separated values use :
scanf("%d,%d,%d", &var1, &var2, &var3);
scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.
Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.
int main()
{
char string[200];
int g,a,i,G[20],A[20],met;
gets(string);
g=convert_input(G,string);
for(i=0;i<=g;i++)
printf("\n%d>>%d",i,G[i]);
return 0;
}
int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
temp=0;
while(string[i]!=' ' && string[i]!='\0')
temp=temp*10 + (string[i++]-'0') ;
if(string[i]==' ')
i++;
K[j++]=temp;
}
return j-1;
}
It should be as simple as using a list of receiving variables:
scanf("%i %i %i", &var1, &var2, &var3);
With this solution, it's possible to read positive and negatives integers:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 50
int convert_input (int * v, char * buffer) {
int len = 0, i = 0, temp = 0, positive_or_negative_one = 1;
while(buffer[i]!='\0') {
temp = 0;
if (buffer[i] == '-'){
positive_or_negative_one = -1;
i++;
} else {
while(buffer[i] != ' ' && buffer[i] != '\0')
temp = temp*10 + (buffer[i++]-'0');
if(buffer[i]==' ')
i++;
v[len++] = temp * positive_or_negative_one;
positive_or_negative_one = 1;
}
}
return len;
}
int main(int argc, char const *argv[]) {
int *a = NULL;
int count_a, len=0;
char buffer[BUFFER_SIZE];
printf("Input numbers here: ");
gets(buffer);
for (int i = 0; i < strlen(buffer); i++) {
if (buffer[i] == ' '){
len+=1;
}
}
a = (int*) malloc(sizeof(int) * len + 1);
count_a = convert_input(a, buffer);
for (int i = 0; i < count_a; i++) {
printf("%d\n", a[i]);
}
free(a);
return 0;
}
Input and output example:
Input numbers here: 1 2 3 -4 10
1
2
3
-4
10

Resources