C converting string/char input to floating point - c

I'm writing a program in C, and one of the requirements is that the user input a number as a string value, and then the program must convert it to floating point format, and then do various things to that value. I can't seem to figure out how to simply convert the input string into a number. How would I write the first chunk of code like that? I know there are posts similar to this, but they haven't been helpful. I need to do this fairly simply, and I'd like to not have to #include anything besides ...
#include <stdio.h>
int main(int argc,char* argv[]) {
/*having issues with this in particular...*/
int number;
int newNumber;
int i;
printf("Enter a number in decimal...");
scanf("%d",&number);
/* */
printf("%d in binary is: ",number);
for(i = 31;i >= 0;i--) {
newNumber = (number>>i);
if(newNumber & 1) {
printf("1");
}
else {
printf("0");
}
}
return 0;
}
Thanks!

Following up on the comment I made:
Your code appears to "work" - in that it reads the input and produces
output. You might consider adding \n at the end of your printf
statements. What exactly isn't working for you? Consider using
8*sizeof(int)-1 rather than 31. You don't know ahead of time how big
an int is on your system.
With a tiny change your code works very nicely for me:
#include <stdio.h>
int main(int argc,char* argv[]) {
/*having issues with this in particular...*/
int number;
int newNumber;
int i;
printf("Enter a number in decimal...\n"); // <<< added a newline
scanf("%d",&number);
/* */
printf("%d in binary is: ",number);
for(i = sizeof(int)*8 - 1;i >= 0;i--) { // make sure `i` starts with the right size
newNumber = (number>>i);
if(newNumber & 1) {
printf("1");
}
else {
printf("0");
}
}
printf("\n"); // <<< print a newline
return 0;
}
When I run it:
Enter a number in decimal...
123
123 in binary is: 00000000000000000000000001111011
note - you do have to input an integer for this to work. If you need your code to be more robust to user "error" in the input, your best bet is to read the input as a string, then do some more parsing. For example:
char buffer[100];
printf("enter an integer:\n");
fgets(buffer, 100, stdin);
// now you can look for spaces, letters, anything you want to skip, in the string
// you could even use sscanf().
// scanf() is a terribly fragile function to use, especially with "free form user input".
if(sscanf(buffer, "%d", &number) == 1) {
// successfully converted number... run your code
} else {
printf("unable to convert input to a number!\n%s\n", buffer);
return 0;
}
another note re-reading your question, you said "program has to convert to a floating point number. This means you should do
float fnumber;
sscanf(buffer, "%f", &fnumber);
or
double dnumber;
sscanf(buffer, "%lf", &dnumber);
to do the conversion. But then, if you want to print as a binary, you need to cast the number from floating point to unsigned integer - a bit shifting operation is not well defined for a floating point number. So
unsigned int *intPtr, number;
intPtr = (unsigned int*) *fnumber; // this is hairy but it works
number = *intPtr;
and now use number as before - you will be able to print out the binary equivalent of the floating point number. There are people who will complain that the above is not "true to the standard". They might prefer it if you created a union:
union f2i
{
float fvalue;
unsigned int ivalue;
} Values;
Then assign the input to Values.fvalue, and use Values.ivalue to print out the binary number. It is still a hack...

You can use strtod(). Read the number into a buffer as a string (say with fgets()), and then do:
double x;
char *endptr;
errno = 0;
x = strtod(buffer, &endptr);
if (endptr == buffer) {
//... parse error or empty input ...
} else if (*endptr != '\n' && *endptr != '\0') {
//... parse error extraneous data ...
} else if ((x == HUGE_VAL || x == -HUGE_VAL) && errno != 0) {
//... error overflow ...
} else if (x <= DBL_MIN && x >= -DBL_MIN) {
if (errno != 0) {
//... error underflow (detected) ....
} else {
// ... underflow still possible, but is undiagnosed ...
}
}
Error checking is done by checking both the value returned for x, and if errno got set. Parse errors is done by checking the endptr. The C standard says underflow detection is implementation defined (C.11 §7.22.1.3 ¶10).

Simple scanf example tested with GCC 4.7.3
$ gcc -Wall -Wextra -pedantic -std=c99 cstring-double.c
#include <stdio.h>
int main() {
double v;
int err;
err = scanf("%lf", &v);
if (1 == err) {
printf("%lf\n", v);
} else {
printf("read failed\n"); }
return 0; }

Just use atof. cplusplus documentation

Related

I have written a C program to convert between decimal, hex and binary

I cant seem to get hexadecimal portion right, I get the right output but the output keeps going on the screen and never stops until i hit ^z. Havent been able to test the rest of the code yet.
/* This program converts decimal to either binary
* or hexadecimal
*/
#include<stdio.h>
#include <string.h>
/*function prints binary of decimal n*/
void binary(unsigned n)
{
/* step 1 recurse dividing by 2*/
if (n > 1)
bin(n / 2);
/* step 2 print bit*/
printf("%d", n % 2);
}
int main(int argc, char const *argv[])
{
char i;
int c;
/* run till ^d entered
*/
while ((i = scanf("%d", &c)) != EOF) {
/* check for argument flag
*/
if (strcmp(argv[1], "-x") == 0)
{
/*convert to hexadecimal and print*/
int decimal = c;
/*read decimal as flag if ^d is not present in flag*/
printf("%s", "0x" );
/*starting 0x formatting for hex*/
printf("%x", decimal);
/*new line for next input*/
printf("\n");
} else if (strcmp(argv[1], "-b") == 0)
{
/* convert to binary and print
*/
int decimal;
/*read decimal as flag if ^d is not present in flag*/
decimal = c;
binary(decimal);
/*new line for next input*/
printf("\n");
} else {
/* prompt help, incorrect flag argument
*/
printf("%s\n", "Usage: ./convert [-x |-b]");
break;
}
}
return 0;
}
I think you meant it to write it like this:
#include <stdio.h>
#include <string.h>
/*function prints binary of decimal n*/
void binary(unsigned n)
{
/* step 1 recurse dividing by 2*/
if (n > 1)
binary(n / 2);
/* step 2: print bit*/
printf("%d", n % 2);
}
int main(int argc, char const * argv [])
{
int num;
signed char should_run = 1;
// make sure that an argument was given
if (argc == 1) {
fprintf(stderr, "Please enter an argument!\n");
should_run = 0;
}
// run until ^d is entered (or an error happened)
while (scanf("%d", &num) > 0 && should_run) {
// convert to hex
if (strcmp(argv [1], "-x") == 0) {
printf("0x%x\n", num);
} // convert to binary
else if (strcmp(argv [1], "-b") == 0) {
binary(num);
printf("\n");
} // print usage
else {
printf("%s\n", "Usage: ./convert [-x |-b]");
should_run = 0;
}
}
return 0;(
}
General improvement-tipps
Check the length of your array before accesing it!
You forgot to check if the user provided one of your arguments (-x, -h). In general this would lead to "easter eggs" (undefined behaviour ;)) since you assume that argv has at least 2 elements in it!
Improve error handling
Well, my "corrected" code isn't a good example either and I think that this is just in exercise, but it's still good to mention: Take care of the possible errors which can appear. In this case I mean the scanf function. It would be nice to add some checks to the return value of it.
Don't split the string to multiple printf statements
You wrote in your code:
/*read decimal as flag if ^d is not present in flag*/
printf("%s", "0x" );
/*starting 0x formatting for hex*/
printf("%x", decimal);
/*new line for next input*/
printf("\n");
which could also be changed to a single line: printf("0x%x\n", decimal) ;)

Determining Data Type Of User Entered Value

I was reading one of the application of "Unions" of creating mixed data types. Example
typedef union {
int x;
float y;
}mix;
mix arr[100];
Each element of array arr[100] can store either a int or a float type value. But suppose I want to take a input from user and store it in arr[ ] and I won't know that either user is going to enter a floator an int value. So I don't know which statement from the following I should choose to store that input from user.
1.scanf ("%d",&arr[0].x);
OR
2.scanf ("%f",&arr[0].y);
And similar problem arises when I want to print that value.
I know I can solve this problem using a "tag field". So I can do it as
#include <stdio.h>
typedef union {
int x;
float y;
}mix;
mix arr[100];
int main ()
{
int k; // tag field
puts("Mention 1 if you want to enter integer and 0 if you want to enter float value");
scanf ("%d",&k);
if (k)
{
scanf ("%d",&arr[0].x);
printf ("%d is the entered integer value\n",arr[0].x);
}
else
{
scanf ("%f",&arr[0].y);
printf ("%f is the entered float value\n",arr[0].y);
}
}
But here user is telling the type of data he is gonna enter(with the help of 0 or 1). I want to know: Is there any way in C language that compiler can automatically detect the type of data user is entering and according run either 1st or 2nd scanf statement without help of user? OR Is there any predefined function present in library for doing that?
Also tell if you have any another intresting way of doing this program.
This might help you I guess...
float num;
printf("Enter number\n");
scanf("%f",&num);
if((num - (int)num)== 0) //(int)num : Type casting
printf("Entered number is of int type\n");
else
printf("Entered number is of float type\n");
Determining Data Type Of User Entered Value
Read as a line fgets()and the parse with strtol(), strtof().
Untested code, read comments.
puts("Mention 1 if you want to enter integer and 0 if you want to enter float value");
char buffer[100];
if (fgets(buffer, sizeof buffer, stdin)) {
// OK we have an input line of text now as a string
buffer[strcspn(buffer, "\n")] = '\0'; // lop off potential \n
char *endptr;
errno = 0;
long lval = strtol(buffer, &endptr);
// If conversion occurred and no text at the end ...
if (endptr > buffer && *endptr == '\0') {
// An integer type!
if (errno == ERANGE) puts("Integer value out of range");
printf("Integer value: %ld\n", lval);
} else {
errno = 0;
float = strtof(buffer, &endptr);
if (endptr > buffer && *endptr == '\0') {
// A float
if (errno == ERANGE) puts("float value out of range");
printf("float value: %g\n", f);
} else
puts("Non-numeric input");
}
}
For a int mystrtoi(const char *str), see ref code.

Is there a way to check if a string can be a float in C?

Checking if it can be an int is easy enough -- just check that every digit is between '0' and '9'. But a float is harder. I found this, but none of the answers really work. Consider this code snippet, based on the top (accepted) answer:
float f;
int ret = sscanf("5.23.fkdj", "%f", &f);
printf("%d", ret);
1 will be printed.
Another answer suggested using strpbrk, to check if certain illegal characters are present, but that wouldn't work either because 5fin7 wouldn't be legal, but inf would.
Yet another answer suggested checking the output of strtod. But consider this:
char *number = "5.53 garbanzo beans"
char *foo;
strtod(number, &foo);
printf("%d", isspace(*foo) || *foo == '\0'));
It'll print 1. But I don't want to remove the isspace call entirely, because " 5.53 " should be a valid number.
Is there a good, elegant, idiomatic way to do what I'm trying to do?
The first answer should work if you combine it with %n, which is the number of characters read:
int len;
float ignore;
char *str = "5.23.fkdj";
int ret = sscanf(str, "%f %n", &ignore, &len);
printf("%d", ret==1 && !str[len]);
!str[len] expression will be false if the string contains characters not included in the float. Also note space after %f to address trailing spaces.
Demo
You could check if - after having read a value using strtod - the remainder consists solely of white spaces. Function strspn can help here, and you can even define "your personal set of white spaces" to consider:
int main() {
char *number = "5.53 garbanzo beans";
char *foo;
double d = strtod(number, &foo);
if (foo == number) {
printf("invalid number.");
}
else if (foo[strspn(foo, " \t\r\n")] != '\0') {
printf("invalid (non-white-space) trailing characters.");
}
else {
printf("valid number: %lf", d);
}
}
Is there a way to check if a string can be a float?
A problem with the sscanf(...,"%f") approach is on overflow, which is UB. Yet it is commonly handled nicely.
Instead use float strtof(const char * restrict nptr, char ** restrict endptr);
int float_test(const char *s) {
char *ednptr;
errno = 0;
float f = strtof(s, &endptr);
if (s == endptr) {
return No_Conversion;
}
while (isspace((unsigned char) *endptr)) { // look past the number for junk
endptr++;
}
if (*endptr) {
return Extra_Junk_At_End;
}
// If desired
// Special cases with with underflow not considered here.
if (errno) {
return errno; // likely under/overflow
}
return Success;
}
This is a variation on the code fragment posted by dasblinkenlight that is slightly simpler and more efficient as strlen(str) could be costly:
const char *str = "5.23.fkdj";
float ignore;
char c;
int ret = sscanf(str, "%f %c", &ignore, &c);
printf("%d", ret == 1);
Explanation: sscanf() returns 1 if and only if a float was converted, followed by optional white space and no other character.
This code is closely based on the answer by dasblinkenlight. I proffer it as food for thought. Some of the answers it gives may not be what you wanted.
#include <stdio.h>
#include <string.h>
static void test_float(const char *str)
{
int len;
float dummy = 0.0;
if (sscanf(str, "%f %n", &dummy, &len) == 1 && len == (int)strlen(str))
printf("[%s] is valid (%.7g)\n", str, dummy);
else
printf("[%s] is not valid (%.7g)\n", str, dummy);
}
int main(void)
{
test_float("5.23.fkdj"); // Invalid
test_float(" 255. "); // Valid
test_float("255.123456"); // Valid
test_float("255.12E456"); // Valid
test_float(" .255 "); // Valid
test_float(" Inf "); // Valid
test_float(" Infinity "); // Valid
test_float(" Nan "); // Valid
test_float(" 255 "); // Valid
test_float(" 0x1.23P-24 "); // Valid
test_float(" 0x1.23 "); // Valid
test_float(" 0x123 "); // Valid
test_float("abc"); // Invalid
test_float(""); // Invalid
test_float(" "); // Invalid
return 0;
}
Testing on a Mac running macOS Sierra 10.12.6 using GCC 7.1.0 as the compiler, I get the output:
[5.23.fkdj] is not valid (5.23)
[ 255. ] is valid (255)
[255.123456] is valid (255.1235)
[255.12E456] is valid (inf)
[ .255 ] is valid (0.255)
[ Inf ] is valid (inf)
[ Infinity ] is valid (inf)
[ Nan ] is valid (nan)
[ 255 ] is valid (255)
[ 0x1.23P-24 ] is valid (6.775372e-08)
[ 0x1.23 ] is valid (1.136719)
[ 0x123 ] is valid (291)
[abc] is not valid (0)
[] is not valid (0)
[ ] is not valid (0)
The hexadecimal numbers are likely to be particularly problematic. The various forms of infinity and not-a-number could be troublesome too. And the one example with an exponent (255.12E456) overflows float and generates an infinity — is that really OK?
Most of the problems raised here are definitional — that is, how do you define what you want to be acceptable. But note that strtod() would accept all the valid strings (and a few of the invalid ones, but other testing would reveal those problems).
Clearly, the test code could be revised to use an array of a structure containing a string and the desired result, and this could be used to iterate through the test cases shown and any extras that you add.
The cast on the result of strlen() avoids a compilation warning (error because I compile with -Werror) — comparison between signed and unsigned integer expressions [-Werror=sign-compare]. If your strings are long enough that the result from strlen() overflows a signed int, you've got other problems pretending they're valid values. OTOH, you might want to experiment with 500 digits after a decimal point — that's valid.
This code notes the comments made to dasblinkenlight's answer:
Leading blank in format
Tricky special circumstances
Outline fix — now adopted in the answer.
Maybe this? Not very good but may do the job. Returns -1 on error 0 on no conversions done and > 0 with converted numbers flags set.
#define INT_CONVERTED (1 << 0)
#define FLOAT_CONVERTED (1 << 1)
int ReadNumber(const char *str, double *db, int *in)
{
int result = (str == NULL || db == NULL || in == NULL) * -1;
int len = 0;
char *tmp;
if (result != -1)
{
tmp = (char *)malloc(strlen(str) + 1);
strcpy(tmp, str);
for (int i = strlen(str) - 1; i >= 0; i--)
{
if (isspace(tmp[i]))
{
tmp[i] = 0;
continue;
}
break;
}
if (strlen(tmp))
{
if (sscanf(tmp, "%lf%n", db, &len) == 1 && strlen(tmp) == len)
{
result |= FLOAT_CONVERTED;
}
if (sscanf(tmp, "%d%n", in, &len) == 1 && strlen(tmp) == len)
{
result |= INT_CONVERTED;
}
}
free(tmp);
}
return result;
}

C Getting decimal input from user issue

I'm trying to write a function to get a decimal input from the user and return the actual value converted from ASCII. However, the function causes the next input from the user to be skipped. As in:
Enter input: 123
Enter input: /* doesn; allow for input */
Enter input: 456
long sum = 0;
int character = fgetc(stdin);
while(character != '\n'){
if(character >= '0' && character <= '9'){
/* convert from ASCII */
character -= '0';
sum = sum * 10 + character;
}
else{
/* reenter number */
}
character = fgetc(stdin);
}
return sum;
To figure out why your code doesn't work, I suggest you post your full code, because problems may lie in the way you call this function.
So before full code is posted, I can just tell you that this code works well on my machine:
#include <stdio.h>
#include <ctype.h>
int getlong();
int main() {
printf("\t%d\n", getlong());
printf("\t%d\n", getlong());
return 0;
}
int getlong() {
long sum = 0;
int character = fgetc(stdin);
while (character != '\n') {
if (isdigit(character)) {
/* convert from ASCII */
character -= '0';
sum = sum * 10 + character;
character = fgetc(stdin);
}
else {
character = fgetc(stdin);
continue;
}
}
return sum;
}
ctype.h is included in order to use isdigit(), while tells you whether a character is decimal digit.
But in fact, you don't have to do everything on your own. Using standard library is more effective and efficient, both for you and for the computer.
For example, you can scan a long integer directly from stdin:
#include <stdio.h>
int main() {
long value;
puts("Please input numbers:");
while (scanf(" %ld", &value) != 1) {
puts("Only numbers are welcome:");
scanf("%*[^\n]");
}
printf("%ld", value);
return 0;
}
Notice the white-space at the beginning of format, this makes scanf() discard all white-space characters(including spaces, newline and tab characters) extracted until a non-white-space character is met.
Or, use strtol(), while is relatively rarely seen:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char buf[80];
char *pEnd;
long value;
do
{
puts("Numbers please:");
if (fgets(buf, 80, stdin) == NULL)
{
perror("fgets()");
return 1;
}
value = strtol(buf, &pEnd, 10);
}
while (*pEnd != '\n');
printf("%ld", value);
return 0;
}
Of course, sscanf() also works, you can just write the code on your own.
From comments:
an extra newline in the stdin buffer...
Try replacing your current method with scanf() using following format string:
char* fmt = "%[^\n]%*c";
It reads everything up to the newline, then consumes the newline. * is an assignment suppressor.
Example: (includes functions to convert input string to float/integer number)
float get_float(void);
long get_int(void);
int main(void)
{
float num_f = get_float();
long num_i = get_int();
return 0;
}
float get_float(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter floating point number and hit return:\n");
scanf(fmt, input);
return strtod(input, dummy);
}
long get_int(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}
Note: These functions are bare bones illustrations of how converting input into number variables might be done, and were written without any error or range checking. As the commenter has stated, it would be worth your while before implementing production versions to read up on strtol() and strtof in detail. (Links are to the Linux man pages, but because both functions are part of the C standard libraries, documentation can also be found on MSDN here and here)
Why not just use fgets and sscanf?
char buf[80];
float n;
if (fgets(buf, 80, stdin) != NULL) {
if (sscanf(buf, "%f", &n) == 1)
printf("%f\n", n);
else
fprintf(stderr, "invalid float\n");
}

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;
}

Resources