我编写了一个包含一个句子并输出一行中的每个单词的代码。但是我也想在每个单词旁边写上它的大小。
输入:
Hi my name is
电流输出:
Hi
my
name
is
所需的输出:
Hi(2)
my(2)
name(4)
is(2)
我当前的代码:
#include <stdio.h>
#define MAX 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 < MAX && (c = getchar()) != EOF && c != '\n')
{
if (c == ' ')
printf("\n");
else
printf("%c", c);
n++;
}
printf("\n");
if (n == MAX) /* read and discard remaining chars in stdin */
while ((c = getchar()) != '\n' && c != EOF);
return 0;
}
我怎样才能做到这一点?
最佳答案
为了完整起见,采用另一种方法在一个调用中读取整个输入,然后将其标记化:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX (100)
int main(void)
{
int result = EXIT_SUCCESS; /* Be optimistic. */
char s[MAX +1];
printf("\n Enter a sentence.\n\n input: ");
/* read up to 100 characters from stdin, print each word on a line */
if (NULL == fgets(s, sizeof s, stdin))
{
if (ferror(stdin))
{
perror("fgets() failed");
result = EXIT_FAILURE;
}
}
else
{
s[strcspn(s, "\r\n")] = '\0'; /* chop off carriage return, line feed, if any */
for (char * pc = strtok(s, " "); NULL != pc; pc = strtok(NULL, " "))
{
printf("%s (%zu)\n", pc, strlen(pc));
}
}
return result;
}
由于从未明确使用读取缓冲区,因此以下变体也是可能的:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX (100)
int main(void)
{
int result = EXIT_SUCCESS; /* Be optimistic. */
printf("\n Enter a sentence.\n\n input: ");
{
/* read up to 100 characters from stdin, print each word on a line */
char * pc = fgets((char[MAX+1]), MAX+1, stdin);
if (NULL == pc)
{
if (ferror(stdin))
{
perror("fgets() failed");
result = EXIT_FAILURE;
}
}
else
{
pc[strcspn(pc, "\r\n")] = '\0'; /* chop off carriage return, line feed, if any */
for (pc = strtok(pc, " "); NULL != pc; pc = strtok(NULL, " "))
{
printf("%s (%zu)\n", pc, strlen(pc));
}
}
}
return result;
}