1行にn個の文字列
scanf
scanfをn回コールすることで、n個の文字列を取得できます。
#define _CRT_SECURE_NO_WARNINGS //visual studioのエラー対策 #include <stdio.h> #include <string.h> int main(void) { char str[100]; int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%s", str); //① puts(str); } return 0; }
【入力】
3
a b c
【出力】
a
b
c
補足
- ①scanfをコールしても、入力ストリーム内の全ての文字列(a b c)が読み込まれるわけではありません。今回のケースでは、1回のscanfのコールで、1個の文字列が読み込まれます。
fgetsとstrtok
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main(void) { char str[100]; char* ptr; int n; fgets(str, sizeof(str), stdin); //① fgets(str, sizeof(str), stdin); ptr = strtok(str, " "); while (ptr != NULL) { puts(ptr); ptr = strtok(NULL, " "); } return 0; }
【入力】
3
a b c
【出力】
a
b
c
補足
- ①文字列の個数を表す3は今回のケースでは不要であるため、リードして入力ストリームを空にします。
コメント