ページ 11

getchar()の改行文字のクリア

Posted: 2016年8月18日(木) 16:10
by Ohagi
getchar()で1文字取得する際に改行文字をどうにかしたいです。

scanf関数の方はWikipediaに詳しい記述があったのでどうにかなりましたが、getchar()関数についてはどのようにすればいいのでしょうか?

コード:

#include <stdio.h>

int main(void)
{
  int ch;
  
  while(1) {
    printf("ch = ");  ch = getchar();
    printf("ascii code = %d\n", ch);
  }

  return 0;
}

Re: getchar()の改行文字のクリア

Posted: 2016年8月18日(木) 21:42
by Dixq (管理人)
> getchar()で1文字取得する際に改行文字をどうにかしたいです。

「改行コードをスキップしたい」ということですかね?それであればこんな関数を作ってみてはどうでしょうか。

コード:

#include <stdio.h>

int my_getchar() {
	int ch;
	while (1) {
		ch = getchar();
		if (ch != '\n') {
			return ch;
		}
	}
}

int main(void)
{
	int ch;

	while (1) {
		printf("ch = ");
		ch = my_getchar();
		printf("ascii code = %d\n", ch);
	}

	return 0;
}

Re: getchar()の改行文字のクリア

Posted: 2016年8月18日(木) 22:18
by Ohagi
管理人様でしょうか?
返信の方ありがとうございます。

C言語初心者でどうすればいいのかよく分かりませんでしたが
そのように改行文字を飛ばす方法があるのですね。

勉強になりました、ありがとうございます。