如何只扫描整数? [英] How to scanf only integer?

查看:55
本文介绍了如何只扫描整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望代码在用户输入整数值之前一直运行.

I want the code to run until the user enters an integer value.

该代码适用于char和char数组.

The code works for char and char arrays.

我已经执行以下操作:

#include<stdio.h>
int main()
{
    int n;
    printf("Please enter an integer: ");
    while(scanf("%d",&n) != 1)
    {
        printf("Please enter an integer: ");
        while(getchar() != '\n');
    }
    printf("You entered: %d\n",n);
    return 0;
}

问题是,如果用户输入浮点值 scanf 会接受它.

The problem is if the user inputs a float value scanf will accept it.

Please enter an integer: abcd
Please enter an integer: a
Please enter an integer: 5.9
You entered: 5

如何避免?

推荐答案

  1. 您采用 scanf().
  2. 你把它扔进了垃圾箱.
  3. 您使用 fgets()来获取整行.
  4. 您可以使用 strtol()将行解析为整数,检查它是否占用了整行.
  1. You take scanf().
  2. You throw it in the bin.
  3. You use fgets() to get an entire line.
  4. You use strtol() to parse the line as an integer, checking if it consumed the entire line.

char *end;
char buf[LINE_MAX];

do {
     if (!fgets(buf, sizeof buf, stdin))
        break;

     // remove \n
     buf[strlen(buf) - 1] = 0;

     int n = strtol(buf, &end, 10);
} while (end != buf + strlen(buf));

这篇关于如何只扫描整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆