#include <stdio.h>
#include <stdlib.h>
int main() {
char c; /* 1. */
int count;
char arr[50];
c = getchar(); /* 2. */
count = 0;
while (c != EOF) { /* 3. and 6. and ... */
arr[count] = c; /* 4. */
++count; /* 5. */
}
return (EXIT_SUCCESS); /* 7. */
}
c
intである必要があります。getchar()は、有効な文字とEOFを区別するためのintを返します
- 文字を読む
- その文字をEOFと比較します。異なる場合は7にジャンプします。
- その文字を配列
arr
、要素に入れますcount
- 配列の次の要素に「別の」文字を配置する準備をします
- 1で読み取った文字のEOFを確認します
ループを通過するたびに異なる文字を読み取る必要があります。(3.、4.、5。)
また、予約したスペースより多くの文字を配列に入れることはできません。(4.)
これを試して:
#include <stdio.h>
#include <stdlib.h>
int main() {
int c; /* int */
int count;
char arr[50];
c = getchar();
count = 0;
while ((count < 50) && (c != EOF)) { /* don't go over the array size! */
arr[count] = c;
++count;
c = getchar(); /* get *another* character */
}
return (EXIT_SUCCESS);
}
編集
配列にキャラクターが入ったら、何かしたいと思うでしょう?したがって、プログラムが終了する前に、それらを印刷するための別のループを追加します。
/* while (...) { ... } */
/* arr now has `count` characters, starting at arr[0] and ending at arr[count-1] */
/* let's print them ... */
/* we need a variable to know when we're at the end of the array. */
/* I'll reuse `c` now */
for (c=0; c<count; c++) {
putchar(c);
}
putchar('\n'); /* make sure there's a newline at the end */
return EXIT_SUCCESS; /* return does not need () */
文字列関数printf()を使用しなかったことに注意してください。文字列ではないため、使用しませんarr
でした。これは、(必然的に)0(NUL)を持たない文字の単純な配列です。NULを含む文字配列のみが文字列です。
NULをarrに入れるには、ループを50文字に制限するのではなく、49文字に制限して(NUL用に1スペース節約)、最後にNULを追加します。ループの後に、
arr[count] = 0;