【问题标题】:Print each word in a separate line from an input string在输入字符串的单独行中打印每个单词
【发布时间】:2015-07-30 00:54:29
【问题描述】:

我在将每个单词与 C 中的输入字符串分开打印时遇到问题。我正在做的作业中的问题是:

将一个句子作为输入,并在单独的行中打印它的单词。

我的代码:

#include<stdio.h>

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

   scanf("%s", s);

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

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

任何帮助将不胜感激。

【问题讨论】:

  • 我认为您在编写可读代码时遇到了问题。
  • 修正您的格式。使用调试器。
  • 另外:在每个单词的末尾打印一个备用的' '

标签: c string char printf scanf


【解决方案1】:
#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");
         }
     }
}

【讨论】:

  • 欢迎来到 SO。为了使答案对 OP 有用,请说明您更改了什么以及为什么
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    下面的代码就是答案。 程序还计算空格/字符数和换行数。

    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#

    在下面输入单词

    你好,你好吗 你好

    如何

    【讨论】:

    • 感谢您提供此代码 sn-p,它可能会提供一些有限的短期帮助。一个正确的解释would greatly improve 其长期价值,通过展示为什么这是解决问题的好方法,并将使其对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。
    【解决方案4】:

    Rookie,使用 line-oriented 输入(如fgetsgetline)通常是读取一行文本的正确方法。但是,在对单个字符进行简单拆分时,一次读取一个字符可能是有利的。

    在您的情况下,如果您的任务是阅读最多 100 个字符的句子并将句子的单词打印在不同的行中,那么没有理由将句子读入数组并存储单词。您可以简单地读取/打印每个字符,直到读取一个空格,然后打印 newline 而不是空格。继续阅读/打印,直到达到 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;
    
    }
    

    使用/输出

    $ ./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 &lt; 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]);
    

    了解两种输入方式,面向字符的输入和面向行的输入将节省您的时间,让您可以根据情况匹配正确的工具。在这里,没有“更正确”或“不太正确”的方法,只有不同的方法。

    【讨论】:

      【解决方案5】:

      在您的代码中,

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

      错了。改成

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

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

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

      此外,虽然scan()%s 配合使用,但您无法将整个 空格分隔的输入读取为单个 字符串。从手册页,

      %s

      匹配一系列非空白字符;下一个指针必须是指向字符数组的指针,该指针的长度足以容纳输入序列和自动添加的终止空字节 ('\0')。 输入字符串在空白处或最大字段宽度处停止,以先发生者为准。

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

      也就是说,

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

      【讨论】:

      • 是的,我放了 get(s) 后它工作了,非常感谢你
      • @Rookie_Coder 从不使用gets(),它坏了。请改用fgets()
      • 当我放 fgets 时它不会编译
      • 它说,函数的参数太少
      • @Rookie_Coder 不客气。 :-) 顺便说一句,您可以考虑 accepting 一个对您有帮助的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      相关资源
      最近更新 更多