首页 > 解决方案 > 无法在将字符串的每个单词写入新行的代码中找到错误

问题描述

我正在编写一个将字符串作为输入并在换行符中打印字符串中的每个单词的代码。

我为此目的使用指针算术

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

int main() {
  char *s;
  s = malloc(1024 * sizeof(char));
  scanf("%[^\n]", s);
  s = realloc(s, strlen(s) + 1);
  while (*s != '\0') {
    if (*s == ' ') {
      printf("\n");
    } else {
      printf("%s", s);
    }
    s++;
  }
  return 0;
}

输入:

i am a beginner. \n  

输出:

i am a beginner \n   
am a beginnerm a beginner \n   
a beginner \n
beginnereginnerginnerinnernnernererr

标签: c

解决方案


我会说除非您需要一些额外的功能或便携性,否则重新发明轮子不是很合乎逻辑。同样可以更可靠地完成,例如:

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

int main()
{
    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);

    char *to_free = s = realloc(s, strlen(s) + 1);
    char *word;

    while ((word = strsep(&s, " \t")) != NULL)
        printf("%s\n", word);

    free(to_free);

    return 0;
}

这还允许您跟踪制表符和空格(当您考虑单词时)。注意传递给 的参数strsep,它是一个空格和一个制表符。只需将这些分隔符添加到参数中,您也可以使用,,.等轻松分隔单词。strsep

释放您分配的内存也是一个好习惯。


推荐阅读