C语言实现读取输入中最前面的整数

来源:互联网 发布:python 爬虫 登录微博 编辑:程序博客网 时间:2024/09/21 09:04

例如,输入123abc,程序读取123;

#include <ctype.h>#include <stdio.h>#include <stdlib.h>/*getint : get next integer from input into *pn*/int getint(int *pn){int c, sign;while (isspace(c = getchar())) {/*skip white space*/}if (!isdigit(c) && c != EOF && c != '+' && c != '-') {putchar(c);/*not a number*/return 0;}sign = (c == '-') ? -1 : 1;if (c == '+' || c == '-') {//获取下一个字符c = getchar();}for (*pn = 0; isdigit(c); c = getchar()) {*pn = *pn * 10 + (c - '0');}//乘以符号*pn *= sign;if (c == EOF) {putchar(c);}return c;}int main(){int *n = malloc(4);getint(n);printf("%d\n", *n);return 0;}


 

原创粉丝点击