#include <stdio.h>
#include <ctype.h>
void main( void )
{
int ch;
int result = 0;
printf( "Enter an integer: " );
/* Read in and convert number: */
while( ((ch = getchar()) != EOF) && isdigit( ch ) )
result = result * 10 + ch - '0'; /* Use digit. */
if( ch != EOF )
ungetc( ch, stdin ); /* Put nondigit back. */
printf( "Number = %d\nNextcharacter in stream = '%c'",
result, getchar() );
}
Output
Enter an integer: 521a Number = 521 Nextcharacter in stream = 'a'
本文介绍了一个简单的C语言程序,该程序能够从用户那里接收整数输入,并展示如何通过使用getchar和isdigit函数来逐个读取并转换数字字符为整数。此外,还展示了如何处理非数字字符。
368

被折叠的 条评论
为什么被折叠?



