简体   繁体   English

我可以使用什么来代替 C 中的 scanf 输入 integer?

[英]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.我正在学习C。我目前正在使用CLion IDE练习C。我之前使用过codeblocksvs code ,还可以。 But Clion is showing an warning for scanf() .但是 Clion 显示了对scanf()的警告。 Is there anything that I can use instead of scanf for taking input like integer, float and double ?有什么我可以用来代替 scanf 来获取integer、float 和 double之类的输入吗?

It will be very grateful for me to know.我将非常感激知道。

Do not use scanf() for user inputs, it has several drawbacks.不要将scanf()用于用户输入,它有几个缺点。

Use fgets() instead.请改用fgets()

Here's anice read (off-site resource) on the "why" part.这是关于“为什么”部分的好读物(场外资源)。

Use fgets() .使用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.这是 CLion IDE 中针对 scanf function 的错误。如果您能说出您收到的警告是什么,我们将不胜感激。

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).如果您不想使用scanf ,您有几个选择:您可以结合使用fgetsstrtol (对于 integer 输入)或strtod (对于浮点输入)。 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.您可以使用getchar读取单个字符,使用isdigit检查每个字符,然后手动构建值。 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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM