Rookie,使用 line-oriented 输入(如fgets 或getline)通常是读取一行文本的正确方法。但是,在对单个字符进行简单拆分时,一次读取一个字符可能是有利的。
在您的情况下,如果您的任务是阅读最多 100 个字符的句子并将句子的单词打印在不同的行中,那么没有理由将句子读入数组并存储单词。您可以简单地读取/打印每个字符,直到读取一个空格,然后打印 newline 而不是空格。继续阅读/打印,直到达到 100 个字符,遇到 newline 或 EOF:
#include <stdio.h>
#define MAXC 100
int main(void) {
int c = 0;
size_t n = 0;
printf ("\n Enter a sentence.\n\n input: ");
/* read up to 100 characters from stdin, print each word on a line */
while (n < MAXC && (c = getchar ()) != EOF && c != '\n')
{
if (c == ' ')
printf ("\n");
else
printf ("%c", c);
n++;
}
printf ("\n");
if (n == MAXC) /* read and discard remaining chars in stdin */
while ((c = getchar ()) != '\n' && c != EOF);
return 0;
}
使用/输出
$ ./bin/getchar_print_nl_space
Enter a sentence.
input: This is a sentence to split into words.
This
is
a
sentence
to
split
into
words.
注意:如果您要存储所有字符,最多 100 个(意味着 99 个字符和 1 个空终止符),您需要将长度检查调整为 n < MAXC - 1 然后为空- 终止数组:
char s[MAXC] = {0};
/* read up to 99 characters from stdin into s */
while (n < MAXC - 1 && (c = getchar ()) != EOF && c != '\n')
s[n++] = c;
s[n] = '\0'; /* null-terminate after last character */
if (n == MAXC - 1) /* read and discard remaining chars in stdin */
while ((c = getchar ()) != '\n' && c != EOF);
然后您将重复逻辑检查空格并在for 循环中打印newline:
for (c = 0; c < n; c++)
if (s[c] == ' ')
printf ("\n");
else
printf ("%c", s[c]);
了解两种输入方式,面向字符的输入和面向行的输入将节省您的时间,让您可以根据情况匹配正确的工具。在这里,没有“更正确”或“不太正确”的方法,只有不同的方法。