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

时间:2013-09-08 16:57:52

标签: c

我想在C中创建一个读取一行字符的程序,然后在不同的行上打印该行中的每个单词。

这就是我所拥有的:

char C;

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

正如你所看到的,我没有开始做我想做的事情,因为我不知道我是否应该使用if-statment或for-statment。

3 个答案:

答案 0 :(得分:2)

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

#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;
}

如果你在一行中有多个空格,我会让你尝试解决问题 - 一旦你理解了这一点,就不会那么难。

答案 1 :(得分:0)

我明白了。现在我已经在这里做了我自己的解决方案,我认为更容易理解:

#include <stdio.h>

void main()
{
char c;

c = getchar();
while(c !='\n')
{
    if (c == ' ')
    {
        printf("\n");
    }
    else
    {
        putchar(c);
    }
    c = getchar();
}
printf("\n");
}

答案 2 :(得分:0)

读取数组中的字符,进行for循环,使用endl语句打印它们,然后运行到最近的书店并获取编程书。