c - 无法从字符串中删除尾随换行符

标签 c newline

我无法从多行字符串中删除尾随的\n,然后将其放入标记中以列出它们以用于表格。该字符串来自使用输入重定向 (< input.txt) 的文本文件。这是我目前所拥有的:

文本文件是:

Little Boy Blue, Come blow your horn, The sheep's in the meadow, The
cow's in the corn; Where is that boy Who looks after the sheep? Under
the haystack Fast asleep. Will you wake him? Oh no, not I, For if I do
He will surely cry.

代码:

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

int main()
{
    int c;
    char *line;
    char *ptr;
    char *pch;
    line = (char *) malloc(1);
    ptr = line;
    for (;( *line = c = tolower(getchar())) != EOF; line++);

    *line='\0';

    pch = strtok(ptr," \n,.-");
    while (pch != NULL) 
    {
        printf ("%s\n", pch);
        pch = strtok(NULL, " ?;,.-");
    }
    return 0;      
}

最佳答案

你有严重的内存分配问题;你分配一个字节的内存,然后尝试向其中读取大量字符,并在末尾添加一个空字节。你需要解决这个问题。

您的代码也有点令人费解,因为分隔符在对 strtok() 的两次调用之间发生了变化。 .这是允许的,但不清楚为什么不在第二个中包含换行符而在第一个中不包含问号和分号(以及感叹号和冒号呢?)。

请注意 tolower()<ctype.h> 中声明.

消除末尾换行符的最简单方法是用空字节覆盖它。如果您还需要映射其他换行符,请在读取数据时进行翻译。

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

int main(void)
{
    int c;
    char *line = (char *)malloc(1);
    size_t l_max = 1;
    char *ptr = line;

    if (line == 0)
        return 1;  // Report out of memory?

    while ((c = tolower(getchar())) != EOF)
    {
        if (ptr == line + l_max - 1)
        {
            char *extra = realloc(line, 2 * l_max);
            if (extra == 0)
                return 1;  // Report out of memory?
            l_max *= 2;
            line = extra;
        }
        *ptr++ = c;
    }

    if (*(ptr - 1) == '\n')
        ptr--;
    *ptr = '\0';

    static const char markers[] = " \n\t,.;:?!-";
    char *pch = strtok(line, markers);

    while (pch != NULL) 
    {
        printf ("%s\n", pch);
        pch = strtok(NULL, markers);
    }
    return 0;      
}

您也可以只在数据中保留换行符; strtok()最终会跳过它。

关于c - 无法从字符串中删除尾随换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26479106/

相关文章:

php 和换行符 : what I need to know?

c - 将从 C 例程分配的数组传递给 Ada

c - Unsigned int 用 UDP 发送后显示为随机负整数

linux - append 到新行

ruby - 如何在输出中换行

c - 在声明的 C 字符串上添加 CRLF

PHP 正则表达式将新行限制为最多两个

c - 错误的 strlen 输出

c - 确定结束数字后在C中循环?

c - 如何链接这两个函数