求一个标准的输入数据方法~
已知用scanf输入数据是有风险的,那么有没有一种比较规范的输入写法例如用fscanf读取一个字符串或者int型的?~并且解决残留缓冲区问题~打算参考一下~
void Input_Data(const char* format,void* data) //输入处理函数 { char str[MAX_BUFF]={0}; fscanf(stdin,"%s",str); while (sscanf(str,format,data)!=1) { while (getchar()!='\n'); puts("输入数据不合法,请重新输入!"); fscanf(stdin,"%s",str); } while (getchar()!='\n'); }
[此贴子已经被作者于2017-9-13 22:05编辑过]
[此贴子已经被作者于2017-9-13 22:06编辑过]
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include "getstring.h" #define INITSIZE 124 char * getstring( FILE *FP ) { char *Temp, *Str; int CurrentSize, lx; int ch; CurrentSize = INITSIZE; Temp = NULL; Str = ( char * )malloc( INITSIZE * sizeof( char ) ); if( NULL != Str ) { for( lx = 0; EOF != ( ch = getc(FP) ) && '\n' != ch; lx++ ) { if( lx == CurrentSize - 1 ) { CurrentSize += INITSIZE; Temp = ( char * )realloc( Str, CurrentSize * sizeof( char ) ); if( NULL == Temp ) { Str[ lx ] = '\0'; return Str; } Str = Temp; } Str[ lx ] = ch; } if( '\n' == ch ) Str[ lx++ ] = '\n'; Str[ lx ] = '\0'; if( 0 == lx ) { free( Str ); Str = NULL; return Str; } if( lx < CurrentSize ) { Temp = ( char * )realloc( Str, ( lx + 1 ) * sizeof( char ) ); if( NULL == Temp ) return Str; Str = Temp; } return Str; } else return NULL; }