简体   繁体   English

为什么此循环无限重复?

[英]Why is this loop infinitely repeating?

The purpose of this program is to count the digits in an alphanumeric input. 该程序的目的是计算字母数字输入中的数字。 However, I used a loop to not execute the program unless the input is alphanumeric . 但是, 除非输入为字母数字,否则我使用循环不执行程序

This is the code: 这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>

int main(){
   int input,isanum,digitcount;
   printf("\nEnter a number: ");
   scanf("%d",&input);
   isanum=isalnum(input);

   while(isanum==0){
     printf("\nIncorrect input. Try again: ");
     scanf("%d",&input);
     isanum=isalnum(input);
   }
   digitcount=0;
   while(input!=0){
       input=input/10;
       digitcount++;
   }
   printf("\nNumber of digits = %d",digitcount);
   return 0;
}

The problem is with the loop. 问题出在循环上。 It keeps looping infinitely and ignores the scanf statement and I don't know why. 它不断循环无限,并忽略scanf语句 ,我不知道为什么。 Am I using isalnum() incorrectly here? 我在这里错误使用isalnum()吗?

You need to check the return value of scanf() . 您需要检查scanf()的返回值。

isalnum() takes a character, but you are passing an int. isalnum()需要一个字符,但是您要传递一个int值。 '1' is not the same as 1 in C. '1'与C中的1不同。

You probably should consume an entire line each time, eg with fgets() , and then check if it fits your desired input format, eg with sscanf() . 您可能应该每次使用一整行,例如使用fgets() ,然后检查它是否符合您想要的输入格式,例如使用sscanf()

As it stands, you never consume anything, you just keep trying to read a number but there isn't one there so it fails every time. 就目前而言,您永远不会消耗任何东西,只是不断尝试读取一个数字,但是那里没有一个数字,因此每次都会失败。 Failing to check the return value of scanf() is a contributing factor to your not noticing this. 未能检查scanf()的返回值是导致您未注意到此问题的一个因素。

Look at how isalnum() is defined: it expects a char * . 看一下isalnum()的定义:它需要一个char * You, however, give it an int * . 但是,您给它一个int * The data is stored completely different there. 数据存储在那里。

Besides, if you are reading in an int, you know beforehand that it will be alphanumeric, right? 此外,如果您正在读取int,则您事先知道它将是字母数字,对吗?

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

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