c - 无法在将字符串的每个单词写入新行的代码中找到错误
问题描述
我正在编写一个将字符串作为输入并在换行符中打印字符串中的每个单词的代码。
我为此目的使用指针算术
#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
解决方案
我会说除非您需要一些额外的功能或便携性,否则重新发明轮子不是很合乎逻辑。同样可以更可靠地完成,例如:
#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
释放您分配的内存也是一个好习惯。
推荐阅读
- android - Network Profiler 显示发送时间远高于接收时间
- python - 将 selenium 中的 .text 输出递归解析为 Django 模型
- php - 使用 PHP 将 JPG 即时合并为一个 PDF
- virtual-machine - 是否有可能从虚拟框中损坏的操作系统中检索文件?
- spring - Spring boot+JSP中GET方法、视图、POST方法如何保持模型对象一致
- html - Bootstrap 在输入组 div 中包装内容
- javascript - Vue 单元测试 - 模拟插件返回值
- apache-zeppelin - 动态表单在 zeppelin spark 解释器中不起作用
- sql - 活动记录嵌套关联
- scala - 如何将 CollectionAccumulator[(Double, Double)] 转换为 SparkdataFrame?