c - 将一行中的每个单词打印在单独的行上

标签 c

我想用 C 编写一个程序,读取一行字符,然后在单独的行上打印该行中的每个单词。

这就是我所拥有的:

char C;

printf("Write some characters: ");
scanf_s("%c",&C);
printf("%c",C);

如您所见,我还没有开始做我想做的事情,因为我不知道是否应该使用 if 语句或 for 语句。

最佳答案

首先,您需要读取整行字符,而您只读取了一个字符:

#include <stdio.h>
#include <string.h>


int main()
{
    int k;
    char line[1024];
    char *p = line; // p points to the beginning of the line

    // Read the line!
    if (fgets(line, sizeof(line), stdin)) {
      // We have a line here, now we will iterate, and we
      // will print word by word:
        while(1){
            char word[256] = {0};
            int i = 0;
            // we are always using new word buffer,
            // but we don't reset p pointer!

            // We will copy character by character from line
            // until we get to the space character (or end of the line,
            // or end of the string).
            while(*p != ' ' && *p != '\0' &&  *p != '\n')
            {
              // check if the word is larger than our word buffer - don't allow
              // overflows! -1 is because we start indexing from 0, and we need
              // last element to place '\0' character! 
              if(i == sizeof(word) - 1)
                 break;

              word[i++] = *p;
              p++;
            }
            // Close the string
            word[i] = '\0';

            // Check for the end of the original string
            if(*p == '\0')
                break;

            // Move p to the next word
            p++;

            // Print it out:
            printf("%s\n", word);
        }
    }

    return 0;
}

如果行中有多个空格,我让您尝试解决问题 - 一旦您了解了这是如何完成的,这并不难。

关于c - 将一行中的每个单词打印在单独的行上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18686295/

相关文章:

c - 字节大小字段的结构填充和对齐?

c - 为指向指针数组的指针分配空间

c - Unix 编程共享内存奇怪的结果

c - 如何从 C 程序读取输出并为程序提供输入?

c++ - C++ 中的 Typedef 错误

C函数,反转字符串

c - C Header 在语言上是什么?

c - 如何创建在内存中分配的数组

c - 获得两个数组的相同长度的最简单方法?

python - 将 C 的 fread(&struct,....) 移植到 Python