Skip to content

Instantly share code, notes, and snippets.

@LilinYume
Last active August 29, 2015 14:18
Show Gist options
  • Save LilinYume/d205f266995485b597e3 to your computer and use it in GitHub Desktop.
Save LilinYume/d205f266995485b597e3 to your computer and use it in GitHub Desktop.
#include "read_number.h"
int read_number(void)
{
char c;
int n;
int m;
int fail;
n = 0;
m = 0;
fail = 0;
/* stdioが行バッファしてくれる事実を前提。 */
while((c=getchar()) != '\n') {
/* 負の整数 */
if(c=='-') {
while((c=getchar()) != '\n') { /* ストリーム上の次を読み取る。 */
if(isdigit(c)) {
m = m*10 + c-'0';
n = -m;
}
else { fail = 1; break; }
}
break;
}
/* 正の整数 */
else if(isdigit(c)) {
n = n*10 + c-'0';
}
/* 数字以外 */
else { fail = 1; break; }
}
if(fail==0) {
return n;
}
else {
fprintf(stderr, "%s\n", "unreadable data detected\n");
return -1;
}
}
//====================================================================
#include "read_number.h"
int main(void)
{
char c;
int n;
int sig;
c = 0;
n = 0;
sig = 1;
/* stdioが行バッファしてくれる事実を前提。 */
while((c=getchar()) != '\n') {
if(c=='-') {
sig = -1;
}
if(isdigit(c)) {
n = n*10 + c-'0';
}
}
n *= sig;
printf("%d\n", n);
return 0;
}
#ifndef READ_NUMBER_H
#define READ_NUMBER_H
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* 数値の読み取り
* 文字として1文字読み取る.
* int の変数に数値として格納.
* '-'から始まる場合は符号を考慮する。
* 十進数の数値文字リテラルにのみ対応 */
int read_number(void);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment