我无法从多行字符串中删除尾随的\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/