C言語のscanf関数でスペースが入っている文字を出力する
auです。
今回はscanf関数でスペースの入った文字を出力してみます。
普通に書こうとすると以下のようになると思います。
#include <stdio.h> int main(void) { char c[30]; printf("Please write words\n"); scanf("%s", c); printf("c = %s\n", c); printf("Please write words\n"); scanf("%s", c); printf("c = %s\n", c); return 0; } // 実行結果 Please write words I have a pen c = I Please write words c = have
scanfでスペースを含めた文字を出したい場合は以下のようにします。
scanf("%[^\n]%*c", c);
このようにすると"\n(改行)"以外出力されるようになります。
上のコードを書き替えてみます。
#include <stdio.h> int main(void) { char c[30]; printf("Please write words\n"); scanf("%[^\n]%*c", c); printf("c = %s\n", c); printf("Please write words\n"); scanf("%s", c); printf("c = %s\n", c); return 0; } // 実行結果 Please write words I have a pen. c = I have a pen. // scanf("%[^\n]%*c", c); Please write words I have a pen. // scanf("%s", c); c = I
%が一つ赤く表示されますが問題なくコンパイルすることができる。
全ての文が出力されました。