在输入字符串的单独行中打印每个单词

Print each word in a separate line from an input string

我无法在 C 语言的输入字符串的单独行中打印每个单词。我正在做的作业中的问题是:

Take a sentence as input and print its words in separate lines.

我的代码:

#include<stdio.h>

int main()
{
   int i;
   char s[100];

   scanf("%s", s);

   for(i=0; s[i]!='[=10=]'; i++)
   {
      printf("%c", s[i]);

      if(s[i]==' ')
      {
         printf("\n");
      }
   }
}

如有任何帮助,我们将不胜感激。

在您的代码中,

  printf("%s", s[i]); 

错了。将其更改为

 printf("%c", s[i]); 

因为,您正在尝试打印 char 值。 char 的转换说明符是 %c.

注意:永远记住,使用错误的转换说明符会导致undefined behaviour

此外,当 scan()-ing 与 %s 结合时,您无法将 整个 space 分隔的输入读取为 单个字符串。从手册页,

%s

Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('[=17=]'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.

您需要使用 fgets() 来完成这项工作。

也就是说,

  1. 正确缩进代码,使其易于阅读。
  2. scanf("%s", s); 更改为 scanf("99%s", s); 以避免可能的缓冲区溢出,方法是放置比 99 chars 更长的输入字符串。
  3. main() 的正确签名是 int main(void)

菜鸟,使用 line-oriented 输入,如 fgetsgetline,通常是阅读一行文本的正确方法。然而,当对单个字符进行简单拆分时,一次读取一个字符可能是有利的。

在您的情况下,如果您的任务是阅读最多 100 个字符的句子并将句子中的单词打印在不同的行中,则没有理由将句子读入数组并存储单词。您可以简单地 read/print 每个字符,直到 space 被读取,然后打印 newline 而不是 space。 reading/printing 一直持续到你达到 100 个字符,遇到 newlineEOF:

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

}

Use/Output

$ ./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] = '[=12=]';        /* null-terminate after last character  */

    if (n == MAXC - 1) /* read and discard remaining chars in stdin */
        while ((c = getchar ()) != '\n' && c != EOF);

然后您将重复 space 的逻辑检查并在 for 循环中打印 newline

    for (c = 0; c < n; c++)
        if (s[c] == ' ')
            printf ("\n");
        else
            printf ("%c", s[c]);

了解两种输入方式,面向字符的输入和面向行的输入将节省您的时间,使您能够匹配正确的工具的情况。在这里,没有 "more correct" 或 "less correct" 方法,只是不同的方法。

下面的代码就是答案。 程序还计算 space/char 和新行的数量。

http://cprograming-char-operation.blogspot.com/2018/07/for-given-statement-print-word-in-each.html

/* Program 1_12 */
/* Count number of line, space and char */
/* Replace a char with specific newline */
/* Add blank space in first input */
#include<stdio.h>

int main()
{
    int c,nl,nc,ns,nt;
    nl=nc=ns=nt=0;
    int d,r, prevd, prevr;
    printf("Enter which char to replace :: ");

    /* prev is stored before of \n */
    while((d = getchar()) != '\n' && (prevd = d));
    d = prevd;
    printf("Enter word below \n");
    while((c=getchar()) != EOF)
    {
        ++nc;
        if(c==' ')
            ++ns;
        if(c=='\n')
            ++nl;
        if(c=='\t')
            ++nt;
        /* Replace a char with A */
        if(c==d)
            putchar('\n');
        else
            putchar(c);
    }
    printf("total char=%2d, newline=%2d, space=%2d tabs=%2d\n",nc,nl,ns,nt);
    return 0;
}

/* Written by: Prakash Katudia <prakash.katudia@gmail.com> */

gcc ./my_code.c

./a.out

输入要替换的字符:: #space#

在下面输入单词

你好你好吗 你好

如何

我认为另一种更好地完成这项工作的方法如下。

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

#define MAX_CHAR 100

int main() {

    char s[100],*c;
    int i = 0;

    scanf("%[^\n]", s);

    //Write your logic to print the tokens of the sentence here.
    for ( c = s; *c != (int)NULL; c++){

        if ( *c == ' '){
            *c = '\n';
        }
    }
    printf("%s",s);
    return 0;
}
#include<stdio.h>
#include<string.h>

int main()
{
     char a[1000];          
     int i,len;                          

     scanf("%[^\n]s",a);
     len=strlen(a);

     for(i=0;i<len;i++)
     {
         if(a[i] !=' ')
         {
             printf("%c", a[i]);  
             printf("\n");
         }
     }
}