[GO] C> Enter a number> fgets () / sscanf ()

Arrangement of the method of inputting only numerical values using scanf () in C code.

Reference http://f4.aaacafe.ne.jp/~pointc/log460.html

Reference http://www9.plala.or.jp/sgwr-t/lib/sscanf.html

Return value It can be 0. For example, if "A" is specified for str and "% d" is specified for the format specification, no input will be made and 0 will be returned.

When the return value is larger than 0, judge it as a numerical value.

http://ideone.com/3dx63s

#include <stdio.h>

int inputNumericValue() {
	int val;
	char buf[512];
	
	printf("[Please enter a number]\n");
	fgets(buf, sizeof(buf), stdin);
	if (sscanf(buf, "%d", &val) > 0) {
		printf(">> %d\n", val);
	} else {
		printf(">> ERROR:It is not a number.\n");
	}
}

int main(void) {
	inputNumericValue();
	inputNumericValue();
	inputNumericValue();
	return 0;
}

stdin


A
3
1
4

result


[Please enter a number]
>> ERROR:It is not a number.
[Please enter a number]
>> 3
[Please enter a number]
>> 1

Recommended Posts

C> Enter a number> fgets () / sscanf ()
ABC129 A, B, C commentary
A1 notation and 26-ary number