Simple C Code Error - c

Does anyone know why I am getting a segfault when I run this code? Valgrind tells me that I have "uninitialized value of size 4" on line 13 if( !isdigit(x) ) and an invalid read size 2 on the same line -- address is not stack'd, malloc'd, or free'd.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
int main()
{
int x;
printf("Please enter a number: ");
scanf("%d", &x);
if( !isdigit(x) )
{
printf("You entered %d\n", x);
}
else
{
printf("You did not enter a valid number!\n");
}
return 0;
}

I think that the problem is that if scanf will fail x will be uninitialized.
It is better to enter data in a character array. Otherwise your code has no sense because you are unable to enter a non-number in an object of type int. Moreover if you enter a number the result of using function isdigit can be unexpected.

I compiled your code with g++, resulting in no segfault.
Entering values of:
5, -1, 27, 43545gbb, and gggg
produced results:
5, -1, 27, 43545, and 1729208414

Try the following :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int x = 0;
char a;
printf("Please enter a number: ");
while(scanf("%d%c",&x,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
do
{
scanf("%c",&a);
}while(a != '\n');
}
printf("You entered %d\n", x);
return 0;
}
The code show you a complex way of how to use scanf. For more information : Working of scanf and checking if input is int
According to the c documentation : isdigit
Prototype:
int isdigit( int ch );
Parameters:
ch - character to classify
Purpose:
Checks if the given character is a numeric character (0123456789).
The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF.
Return value:
Non-zero value (true) if the character is a numeric character, 0 (false) otherwise.

Why the problem on Line 13?. Line 13 is if( !isdigit(x) )
You did not initialize x when you created it on line 8,
Therefore, if an unacceptable value is entered, and processed by scanf() on line 11, it will continue to be uninitialized by the time it gets to the isdigit() function.
The problem is that isdigit() expects The input must be a character with integer value between 0 and 255. Any other value will lead to undefined behavior. Segfaults are one of the possible outcomes of undefined behavior.
There are other ways to implement this, for example:
Here is an example using a char array (string). Note the comments to explain why certain things were done.
int main()
{
//int x;
char x[2]; //Good for only one digit
printf("Please enter an integer with up to 10 digits: ");
//scanf("%d", &x);
scanf("%1s", x); //Edited to allow maximum field width of 1.
// if( !isdigit(x) )
if( isdigit(x[0]) ) //note the "!" was removed for logic to work
{
printf("You entered %d\n", atoi(x)); //note use of atoi() to convert string to int.
}
else
{
printf("You did not enter a valid number!\n");
}
return 0;
}

Related

isalpha() and isdigit() always return 0

I have no idea why isdigit() and isalpha() keep doing this. No matter how I use them they always return a 0. Am I using them incorrectly or is my compiler acting up?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
//example of isdigit not working, it ALWAYS returns 0 no matter what the input is.
int main()
{
int num=0;
int check=0;
printf("Enter a number: ");
fflush(stdin);
scanf("%d",&num);
//Just checking what value isdigit has returned
check=isdigit(num);
printf("%d\n",check);
if(check!=0)
{
printf("Something something");
system("pause");
return 0;
}
else
{
system("pause");
return 0;
}
}
isdigit acts on an int, but it is supposed to be char extended to an int. You are reading a number and convert it to a binary representation, so unless your inout happens to be a value matching 0 - ยด9` (i.e. 0x30 - 0x39) you will get false as a result.
If you want to use isdigit() you must use it on the individual characters from the string the user enters as the number, so you should use %s, or %c for single digits, and loop through the string.
Example:
char c;
scanf("%c",&c);
check=isdigit(c);
or (quick and dirty example)
char buffer[200];
if (scanf("%s", buffer) > 1)
{
int i;
for(i = 0; buffer[i] != 0; i++)
{
check=isdigit(buffer[i]);
}
}
Change your scanf ("%d"...) with scanf ("%c"...) and the definition of num from int to char. You may also change the variable name, as isalpha() and isdigit() don't work with "numbers" but with "ASCII codes of characters" (which are indeed numbers), and the prompt message from "Enter a number" to "Enter a character"
You should pass the number character by character to isdigit. Replace %d specifier by %c in scanf. And also remove the line
fflush(stdin);
it may invokes undefined behavior (if you are not on MS-DOS).
You want to check a character not number. 0 and '0' are not the same. The first one is integer, second one is character.
Change on this:
char character =0;
int check = 0;
printf("Enter a number: ");
scanf("%c", &character);
printf("%d\n",character);
check = isdigit(character);
if(check != 0) {
printf("Something something\n");
return 0;
}
else{
return 0;
}
In action:
Enter a number: 5
53 # ASCII code of 5
2048
Something something
Enter a number: a
97 #ASCII code if a
0

Accept Numerical Values only for input using scanf

How can I make sure the user inputs numerical values only instead of alphanumeric or any other character? Also what to look for to insert error message for incorrent input?
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter first number to add\n");
scanf("%d",&a);
printf("Enter second number to add\n");
scanf("%d",&b);
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
If you really want to deal with user input that could be hostile use a separate function for getting the number.
Allows
- leading spaces : " 123"
- trailing spaces : "123 "
- leading zeros : "0000000000000000000000000000000000123"
- Rescans nicely after error input.
Catches the following errors
- No input : ""
- Extra text after the number: "123 abc"
- Text before the number : "abc 123"
- Split number : "123 456"
- Overflow/underflow : "12345678901234567890"
- other : "--123"
Re-prompts on invalid input.
#include <errno.h>
#include <stdio.h>
#include <stddef.h>
int GetInteger(const char *prompt, int *i) {
int Invalid = 0;
int EndIndex;
char buffer[100];
do {
if (Invalid)
fputs("Invalid input, try again.\n", stdout);
Invalid = 1;
fputs(prompt, stdout);
if (NULL == fgets(buffer, sizeof(buffer), stdin))
return 1;
errno = 0;
} while ((1 != sscanf(buffer, "%d %n", i, &EndIndex)) || buffer[EndIndex] || errno);
return 0;
}
int main() {
int a, b, c;
if (GetInteger("Enter first number to add\n", &a)) {
; // End of file or I/O error (rare)
}
if (GetInteger("Enter second number to add\n", &b)) {
; // End of file or I/O error (rare)
}
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
BTW, You should not do printf("Enter first number to add\n"). Use fputs() instead. Consider what would happen if the string had a % in it.
It's better to avoid using scanf at all. Use fgets to get entire line, and then use sscanf to extract the information you need. Check the return value of sscanf to make sure the input is as expected.
Please read the manual page for scanf. You need to check the return value. SHould return 1 if able to match a number.
EDIT- I needed to add the getchar() in the while loop because the unread non-numeric item was left in the input queue causing the program to go in an infinite loop , further I have also added more compact form of while loop for the same thing , both will have the same effect .
You can check the return value of scanf it returns 1 on successful match with the format specifier and 0 if not . You can do it like this for your program :
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool status;//_bool may also be used and stdbool.h won't be needed for that
status = scanf ("%d",&num);
if (status != 1 )
{
getchar();// needed to add it to eat up the unread item left in input queue.
while (status != 1)
{
printf (" sorry ! incorrect input :ERROR: try again");
status = scanf("%d", &num);
}
}
/*....do something...*/
return 0;
}
More compact form of while loop :-
while (scanf("%d",&num) != 1)
{
getchar();
printf (" sorry ! incorrect input :ERROR: try again\n");
}
Besides, you should always use meaningful names for variables like num1 and num2 for instance instead of a and b .

How to ignore floating number in scanf("%d")?

If user enters floating number for an integer variable I want to print invalid input. is that possible?
int a;
scanf("%d",&a); // if user enters 4.35 print invalid input
I have tried for characters like this
if(scanf("%d",&a)==1);
else printf("invalid input");
But how to do for floating numbers. If user enters 4.35 it truncates to 4 but I want invalid input.
Since the start of a floating point number with any digits before the decimal point looks like an integer, there is no way to detect this with %d alone.
You might consider reading the whole line with fgets() and then analyzing with sscanf():
int a;
int n;
char line[4096];
if (fgets(line, sizeof(line), stdin) != 0 && sscanf(line, "%d%n", &a, &n) == 1)
...analyze the character at line[n] for validity...
(And yes, I did mean to compare with 1; the %n conversion specifications are not counted in the return value from sscanf() et al.)
One thing that scanf() does which this code does not do is to skip blank lines before the number is entered. If that matters, you have to code a loop to read up to the (non-empty) line, and then parse the non-empty line. You also need to decide how much trailing junk (if any) on the line is tolerated. Are blanks allowed? Tabs? Alpha characters? Punctuation?
You'll have to read it as a double and then check if it is an integer. The best way to check if it is an integer is to use modf, which returns the decimal portion of the double. If there is one you have an error:
double d;
scanf("%lf", &d);
double temp;
if(modf(d, &temp)){
// Handle error for invalid input
}
int a = (int)temp;
This will allow integers or floating point numbers with only 0s after the decimal point such as 54.00000. If you want to consider that as invalid as well, you are better off reading character by character and verifying that each character is between 0 and 9 (ascii 48 to 57).
This can not be done with out reading pass the int to see what stopped the scan.
Classic idiom
char buf[100];
if (fgets(buf, sizeo(buf), stdin) == NULL) {
; // deal with EOF or I/O error
}
int a;
char ch;
if (1 != sscanf(buf, "%d %c", &a, &ch)) {
; // Error: extra non-white space text
}
You can do it using strtol() and strtod() and comparing the end pointers, e.g. this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char buffer[100];
char * endptr_n;
char * endptr_d;
long n;
double d;
fgets(buffer, 100, stdin);
n = strtol(buffer, &endptr_n, 10);
if ( endptr_n == buffer ) {
fputs("You didn't enter a number.", stderr);
return EXIT_FAILURE;
}
d = strtod(buffer, &endptr_d);
if ( *endptr_d == '\0' || *endptr_d == '\n' ) {
if ( endptr_d == endptr_n ) {
puts("You entered just a plain integer.");
} else {
puts("You entered a floating point number - invalid.");
}
} else {
puts("You entered garbage after the number - invalid.");
}
return EXIT_SUCCESS;
}
outputs:
paul#local:~/src/c$ ./testint
2
You entered just a plain integer.
paul#local:~/src/c$ ./testint
2.3
You entered a floating point number - invalid.
paul#local:~/src/c$ ./testint
3e4
You entered a floating point number - invalid.
paul#local:~/src/c$ ./testint
4e-5
You entered a floating point number - invalid.
paul#local:~/src/c$ ./testint
423captainpicard
You entered garbage after the number - invalid.
paul#local:~/src/c$
It doesn't use scanf(), but that's a good thing, and it avoids the need to manually check the input following the integer you read.
Obviously, if the only thing on the line is the number, then a lot of this becomes unnecessary, since you can just call strtol() and check *endptr_n immediately, but if there may be other stuff on the line this is how you can do it, e.g. if you want to accept an integer followed by anything non-numeric, but not a floating point followed by the same thing, you can just remove the if ( *endptr_d == '\0' || *endptr_d == '\n' ) logic.
EDIT: updated the code to show the check to *endptr.
This one is bit easier:
#include <stdio.h>
int main()
{
int a;
long double b;
scanf("%f",&b);
a = (int) b;
a == b ? printf("%d\n",a) : printf("Invalid input!");
return 0;
}
Input: 4
Output:
4
Input: 4.35
Output:
Invalid input
Here's an easy way:
#include <stdio.h>
int main(int argc, char **argv) {
int d;
printf("Type something: ");
// make sure you read %d and the next one is '\n'
if( scanf("%d", &d) == 1 && getchar() == '\n' ) {
printf("%d\n", d);
}
return 0;
}
.
$ a.exe
Type something: 312312.4214
$ a.exe
Type something: 2312312
2312312
$ a.exe
Type something: 4324.
$
First of all, there is nothing wrong with scanf. When a user enters a float then they actually type in a number dot number. So, code a scanf to detect that data entry.
main()
{
char c1[2];
int num1;
int nr_nums;
nr_nums = scanf("%d%1[.e0123456789]", &num1, &c1);
if (nr_nums == 1) {printf("\ndata = %d", num1);}
if (nr_nums == 2) {printf("\nInvalid");}
}
Modified this code per another possible data entry format of 1. or 3e-1 as suggested by a comment.
This code gets to the basics of your requirement. It accepts Integer data entry and detects when a float is entered.
If you have your number represented as a string (when you have used fgets) you can run a for loop through it and compare each character to '.'.
One other option I can see follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char mystring[31];
scanf("%30s[0-9]\n", mystring);
int mynumber = atoi(mystring);
printf("here is your integer: %d", mynumber);
getchar();
getchar();
return 0;
}

How to invalidate an input in c

I'm writing a program in C that is suppose to ask the user for a number.
The number has to be greater than zero and cannot have letters before or after the number. (ie: 400 is valid but abc or 400abc or abc400 is not). I can make my program invalidate everything besides 400abc. How would I make it invalidate an input if it starts valid then turns invalid? (I'm about 2 months into an intro to c class so my knowledge is very limited.)
#include<stdio.h>
int check(void);
void clear_input(void);
main()
{
int num;
printf("Please enter a number: ");
num = check();
printf("In Main %d\n", num);
}
int check(void){
int c;
scanf("%d", &c);
while (c < 0){
clear_input();
printf("Invalid, please enter an integer: ");
scanf("%d", &c);
}
return c;
}
void clear_input(void){
char junk;
do{
scanf("%c", &junk);
}while (junk != '\n');
}
You can also check whether ascii value of each char scanned from user input should lie in range 48-57, It will only then be integer value.
strtol can be used to do it, but it takes some extra work.
After running this code:
char *endptr;
int n = strtol(num_text, &endptr, 10);
n will contain the number. But you still have to check that:
1. *endptr=='\0' - this means strtol didn't stop in the middle. In 400abc, endptr will point to abc. You may want to allow trailing whitespace (in this case, check that endptr points to an all-whitespace string.
2. num_text isn't empty. In this case, strtol will return 0, but an empty string isn't a valid number.
Read the input as a line, using fgets.
Check if all characters are numeric.
If not, it's invalid. If yes, use sscanf to get the line into an int.
Check if the int is in the range; you're done.
Scanf with %d will treat the "400abc" as 400, all the trailing characters would be ignored, so there is nothing to worry about.
If you definitely want to treat "400abc" as an invalid input, then maybe you shouldn't use %d in scanf, use %s instead?
One way is to read the whole line as a string and check by yourself if it contains any non-digits.
The other way is reading the integer and then looking into the input using fgetc() to see if the next character after the detected input is valid. Or you could even use the same scanf() for this:
char delim;
if(scanf("%d%c", &c, &delim) == 2 && !isspace(delim))
// the input is invalid
You can read the number in a character array and validate it by checking if all the characters lie in the ascii range 48 to 57 ( '0' to '9' ) .If so your no. is valid otherwise you can safely regard it as invalid input.Here the the demonstration :
#include<stdio.h>
#include<string.h>
int conv( char * word )
{
int ans=0;
int res=0;
for(int i=0;i<strlen(word);i++)
if(word[i]>='0' && word[i]<='9')
ans=(ans*10) + (word[i] - '0');
else
res=-999;
if(res==-999)
return res;
else
return ans;
}
int main()
{
char a[10];
gets(a);
int b=conv(a);
if(b==-999)
printf("Invalid Entry.\n");
else
printf("Success.No is %d.\n",b);
return 0;
}
You can adjust for negatives as well by checking the first character in the word array to be '-' and adjusting the sign accordingly.
This is C99, so compile with -std=c99
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
bool getNum(int *n) {
char c, s[10];
if (!scanf("%9s", s))
return false;
for (int i=0; c=s[i]; i++)
if (!isdigit(c))
return false;
*n = atoi(s);
return true;
}
int main() {
int n;
if (getNum(&n))
printf("you entered %d\n", n);
else
printf("you did not enter a number\n");
}
The following is your check function rewritten to fix your problem, so try this:
int check(void){
int n;
char c;
while (EOF==scanf("%d%c", &n,&c) || n < 0 || !isspace(c)){
clear_input();
printf("Invalid, please enter an integer: ");
}
return n;
}

Check if input is integer type in C

The catch is that I cannot use atoi or any other function like that (I'm pretty sure we're supposed to rely on mathematical operations).
int num;
scanf("%d",&num);
if(/* num is not integer */) {
printf("enter integer");
return;
}
I've tried:
(num*2)/2 == num
num%1==0
if(scanf("%d",&num)!=1)
but none of these worked.
Any ideas?
num will always contain an integer because it's an int. The real problem with your code is that you don't check the scanf return value. scanf returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).
As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can't be simply achieved by scanf("%d\n"), but here's a trick to do it:
int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");
You need to read your input as a string first, then parse the string to see if it contains valid numeric characters. If it does then you can convert it to an integer.
char s[MAX_LINE];
valid = FALSE;
fgets(s, sizeof(s), stdin);
len = strlen(s);
while (len > 0 && isspace(s[len - 1]))
len--; // strip trailing newline or other white space
if (len > 0)
{
valid = TRUE;
for (i = 0; i < len; ++i)
{
if (!isdigit(s[i]))
{
valid = FALSE;
break;
}
}
}
There are several problems with using scanf with the %d conversion specifier to do this:
If the input string starts with a valid integer (such as "12abc"), then the "12" will be read from the input stream and converted and assigned to num, and scanf will return 1, so you'll indicate success when you (probably) shouldn't;
If the input string doesn't start with a digit, then scanf will not read any characters from the input stream, num will not be changed, and the return value will be 0;
You don't specify if you need to handle non-decimal formats, but this won't work if you have to handle integer values in octal or hexadecimal formats (0x1a). The %i conversion specifier handles decimal, octal, and hexadecimal formats, but you still have the first two problems.
First of all, you'll need to read the input as a string (preferably using fgets). If you aren't allowed to use atoi, you probably aren't allowed to use strtol either. So you'll need to examine each character in the string. The safe way to check for digit values is to use the isdigit library function (there are also the isodigit and isxdigit functions for checking octal and hexadecimal digits, respectively), such as
while (*input && isdigit(*input))
input++;
(if you're not even allowed to use isdigit, isodigit, or isxdigit, then slap your teacher/professor for making the assignment harder than it really needs to be).
If you need to be able to handle octal or hex formats, then it gets a little more complicated. The C convention is for octal formats to have a leading 0 digit and for hex formats to have a leading 0x. So, if the first non-whitespace character is a 0, you have to check the next character before you can know which non-decimal format to use.
The basic outline is
If the first non-whitespace character is not a '-', '+', '0', or non-zero decimal digit, then this is not a valid integer string;
If the first non-whitespace character is '-', then this is a negative value, otherwise we assume a positive value;
If the first character is '+', then this is a positive value;
If the first non-whitespace and non-sign character is a non-zero decimal digit, then the input is in decimal format, and you will use isdigit to check the remaining characters;
If the first non-whitespace and non-sign character is a '0', then the input is in either octal or hexadecimal format;
If the first non-whitespace and non-sign character was a '0' and the next character is a digit from '0' to '7', then the input is in octal format, and you will use isodigit to check the remaining characters;
If the first non-whitespace and non-sign character was a 0 and the second character is x or X, then the input is in hexadecimal format and you will use isxdigit to check the remaining characters;
If any of the remaining characters do not satisfy the check function specified above, then this is not a valid integer string.
First ask yourself how you would ever expect this code to NOT return an integer:
int num;
scanf("%d",&num);
You specified the variable as type integer, then you scanf, but only for an integer (%d).
What else could it possibly contain at this point?
If anyone else comes up with this question, i've written a program, that keeps asking to input a number, if user's input is not integer, and finishes when an integer number is accepted
#include<stdlib.h>
#include<stdio.h>
#include<stdbool.h>
bool digit_check(char key[])
{
for(int i = 0; i < strlen(key); i++)
{
if(isdigit(key[i])==0)
{
return false;
}
}
return true;
}
void main()
{
char stroka[10];
do{
printf("Input a number: ");
scanf("%s",stroka);}
while (!digit_check(stroka));
printf("Number is accepted, input finished!\n");
system("pause");
}
I looked over everyone's input above, which was very useful, and made a function which was appropriate for my own application. The function is really only evaluating that the user's input is not a "0", but it was good enough for my purpose. Hope this helps!
#include<stdio.h>
int iFunctErrorCheck(int iLowerBound, int iUpperBound){
int iUserInput=0;
while (iUserInput==0){
scanf("%i", &iUserInput);
if (iUserInput==0){
printf("Please enter an integer (%i-%i).\n", iLowerBound, iUpperBound);
getchar();
}
if ((iUserInput!=0) && (iUserInput<iLowerBound || iUserInput>iUpperBound)){
printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
iUserInput=0;
}
}
return iUserInput;
}
Try this...
#include <stdio.h>
int main (void)
{
float a;
int q;
printf("\nInsert number\t");
scanf("%f",&a);
q=(int)a;
++q;
if((q - a) != 1)
printf("\nThe number is not an integer\n\n");
else
printf("\nThe number is an integer\n\n");
return 0;
}
This is a more user-friendly one I guess :
#include<stdio.h>
/* This program checks if the entered input is an integer
* or provides an option for the user to re-enter.
*/
int getint()
{
int x;
char c;
printf("\nEnter an integer (say -1 or 26 or so ): ");
while( scanf("%d",&x) != 1 )
{
c=getchar();
printf("You have entered ");
putchar(c);
printf(" in the input which is not an integer");
while ( getchar() != '\n' )
; //wasting the buffer till the next new line
printf("\nEnter an integer (say -1 or 26 or so ): ");
}
return x;
}
int main(void)
{
int x;
x=getint();
printf("Main Function =>\n");
printf("Integer : %d\n",x);
return 0;
}
I developed this logic using gets and away from scanf hassle:
void readValidateInput() {
char str[10] = { '\0' };
readStdin: fgets(str, 10, stdin);
//printf("fgets is returning %s\n", str);
int numerical = 1;
int i = 0;
for (i = 0; i < 10; i++) {
//printf("Digit at str[%d] is %c\n", i, str[i]);
//printf("numerical = %d\n", numerical);
if (isdigit(str[i]) == 0) {
if (str[i] == '\n')break;
numerical = 0;
//printf("numerical changed= %d\n", numerical);
break;
}
}
if (!numerical) {
printf("This is not a valid number of tasks, you need to enter at least 1 task\n");
goto readStdin;
}
else if (str[i] == '\n') {
str[i] = '\0';
numOfTasks = atoi(str);
//printf("Captured Number of tasks from stdin is %d\n", numOfTasks);
}
}
printf("type a number ");
int converted = scanf("%d", &a);
printf("\n");
if( converted == 0)
{
printf("enter integer");
system("PAUSE \n");
return 0;
}
scanf() returns the number of format specifiers that match, so will return zero if the text entered cannot be interpreted as a decimal integer
The way I worked around this question was using cs50.h library. So, the header goes:
#include <cs50.h>
There you have get_int function and you simply use it for variable initiation:
int a = get_int("Your number is: ");
If a user inputs anything but integer, output repeats the line "Your number is: "; and so on until the integer is being written.
I've been searching for a simpler solution using only loops and if statements, and this is what I came up with. The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.
#include <stdio.h>
#include <stdlib.h> // Used for atoi() function
#include <string.h> // Used for strlen() function
#define TRUE 1
#define FALSE 0
int main(void)
{
char n[10]; // Limits characters to the equivalent of the 32 bits integers limit (10 digits)
int intTest;
printf("Give me an int: ");
do
{
scanf(" %s", n);
intTest = TRUE; // Sets the default for the integer test variable to TRUE
int i = 0, l = strlen(n);
if (n[0] == '-') // Tests for the negative sign to correctly handle negative integer values
i++;
while (i < l)
{
if (n[i] < '0' || n[i] > '9') // Tests the string characters for non-integer values
{
intTest = FALSE; // Changes intTest variable from TRUE to FALSE and breaks the loop early
break;
}
i++;
}
if (intTest == TRUE)
printf("%i\n", atoi(n)); // Converts the string to an integer and prints the integer value
else
printf("Retry: "); // Prints "Retry:" if tested FALSE
}
while (intTest == FALSE); // Continues to ask the user to input a valid integer value
return 0;
}
Just check is your number has any difference with float version of it, or not.
float num;
scanf("%f",&num);
if(num != (int)num) {
printf("it's not an integer");
return;
}
This method works for everything (integers and even doubles) except zero (it calls it invalid):
The while loop is just for the repetitive user input. Basically it checks if the integer x/x = 1. If it does (as it would with a number), its an integer/double. If it doesn't, it obviously it isn't. Zero fails the test though.
#include <stdio.h>
#include <math.h>
void main () {
double x;
int notDouble;
int true = 1;
while(true) {
printf("Input an integer: \n");
scanf("%lf", &x);
if (x/x != 1) {
notDouble = 1;
fflush(stdin);
}
if (notDouble != 1) {
printf("Input is valid\n");
}
else {
printf("Input is invalid\n");
}
notDouble = 0;
}
}
I was having the same problem, finally figured out what to do:
#include <stdio.h>
#include <conio.h>
int main ()
{
int x;
float check;
reprocess:
printf ("enter a integer number:");
scanf ("%f", &check);
x=check;
if (x==check)
printf("\nYour number is %d", x);
else
{
printf("\nThis is not an integer number, please insert an integer!\n\n");
goto reprocess;
}
_getch();
return 0;
}
I found a way to check whether the input given is an integer or not using atoi() function .
Read the input as a string, and use atoi() function to convert the string in to an integer.
atoi() function returns the integer number if the input string contains integer, else it will return 0. You can check the return value of the atoi() function to know whether the input given is an integer or not.
There are lot more functions to convert a string into long, double etc., Check the standard library "stdlib.h" for more.
Note : It works only for non-zero numbers.
#include<stdio.h>
#include<stdlib.h>
int main() {
char *string;
int number;
printf("Enter a number :");
string = scanf("%s", string);
number = atoi(string);
if(number != 0)
printf("The number is %d\n", number);
else
printf("Not a number !!!\n");
return 0;
}

Resources