user13926977
user13926977

Reputation:

What can I use for taking integer input instead of scanf in C?

I am learning C. I am currently using CLion IDE for practicing C. I used codeblocks and vs code before and was ok. But Clion is showing an warning for scanf(). Is there anything that I can use instead of scanf for taking input like integer, float and double?

It will be very grateful for me to know.

Upvotes: 0

Views: 136

Answers (3)

John Bode
John Bode

Reputation: 123458

If you don't want to use scanf, you have a couple of choices: You can use a combination of fgets and strtol (for integer inputs) or strtod (for floating point inputs). Example (untested):

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
...
char buf[12]; // 10 digits, plus sign, plus terminator
char *chk; // points to first character *not* converted by strtol

if ( !fgets( buf, sizeof buf, stdin ) )
{
  fprintf( stderr, "Error on input\n" );
  return EXIT_FAILURE;
}

long value = strtol( buf, &chk, 10 ); // 10 means we expect decimal input
if ( !isspace( *chk ) && *chk != 0 )
{
  fprintf( stderr, "Found non-decimal character %c in %s\n", *chk, buf );
  fprintf( stderr, "value may have been truncated\n" );
}
printf( "Input value is %ld\n", value );

You can use getchar to read individual characters, use isdigit to check each, and build the value manually. Example (also untested):

#include <stdio.h>
#include <ctype.h>
...
int value = 0;
for ( int c = getchar(); isdigit( c ); c = getchar() ) // again, assumes decimal input
{
  value *= 10;
  value += c - '0';
}
printf( "Value is %d\n", value );

Upvotes: 0

Anonymous
Anonymous

Reputation: 92

Use fgets() . It is a bug in CLion IDE for scanf function. It would be more appreciated if you could tell what is the warning you are getting .

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

Do not use scanf() for user inputs, it has several drawbacks.

Use fgets() instead.

Here's a nice read (off-site resource) on the "why" part.

Upvotes: 4

Related Questions