#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() 返回一个 int 来区分有效字符和 EOF
- 读一个字符
- 将该字符与 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 保留一个空格)并在末尾添加 NUL。在循环之后,添加
arr[count] = 0;