0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

十進数よみとり

Last updated at Posted at 2015-03-01

ひまだからてきとうに書いた。


100byte のメモリに溜める
[1][2][3]...[99][100] 
 ^ 開始位置         ^ full


一文字よみこむと次の位置をさす

[1][2][3]...[99][100]
       ^ 3文字よみとったとこ


char buff[100];
const char* n = "100\n2\na5";

char terminator;
char delim;
int fail;
int pos;
 
terminator = '\0';
delim = '\n';
fail = 0;
pos = 0;
 
for(; pos<100 && n[pos] != terminator; ++pos) {
  if(isdigit(n[pos]) || n[pos] == delim) {
    buff[pos] = n[pos];
  }
  else if(n[pos] != delim) {
    fail = 1;
    break;
  }
}
/* ここの pos: 6byte目, 'a'のとこ */

あれ?int full ないなバッファ溢れ放題。

文字配列->すうち にする(`・ω・´)シャキーン


int z = 0;
int i = 0;
 
while(i < pos) {
  if(buff[i] != delim) {
  z = z*10 + buff[i]-'0';
  }
  else break;
   ++i;
  }
}

pos は static でも再帰でもドーゾ。
再帰呼び出しオススメ。

いずれにせよStreamではなくバッファなのです。


追加

行バッファされた1行の読み取りを想定
数字以外だとよみとばす。


  int n;
  if( 1 < (scanf("%d", &n)) ) {
    while( getchar() != '\n'); /* (-人-)改行コードがきますように */
    scanf("%d", &n);
  }


  char c;
  int n;
  int sig;
 
  c = 0;
  n = 0;
  sig = 1;
 
  while((c=getchar()) != '\n') {
    if(c=='-') sig = -1;
    if(isdigit(c)) {
      n = n*10 + c-'0';
    }
  }
  n *= sig;
  return n;

アドバイスもらったヾ(*´∀`*)ノキャッキャ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?