gpt4 book ai didi

c - 如何摆脱单词之间的换行符?

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:21 25 4
gpt4 key购买 nike

我正在学习 C 语言和系统编程。我正在尝试读取一个文本文件并以小写形式打印出单词。所有非字母字符都是定界符。我得到下面的输出。有人可以看看我的代码并给我一些关于如何删除单词之间的行的提示吗?谢谢!

这是我的文本文件的开头:

荷马的伊利亚特古腾堡计划电子书,荷马着

这本电子书可供任何人在任何地方免费使用,并且几乎没有任何限制。您可以复制、赠送或根据 Project Gutenberg License 的条款重新使用它使用这本电子书或访问 www.gutenberg.org 在线访问

标题:荷马的伊利亚特

作者:荷马

译者:Andrew Lang, M.A., Walter Leaf, Litt.D., 和 Ernest Myers, M.A.

发布日期:2012 年 1 月 14 日 [电子书 #3059]发布日期:2002 年 2 月

语言:英语

这是我的输出:这项目古腾堡电子书的这伊利亚特的荷马

由荷马

这个电子书是为了这使用的任何人任何地方在不成本和和几乎不限制随便

你可能复制它

给予它离开或者关于使用它在下面这条款的这项目古腾堡执照包括和这电子书或者在线的在万维网古腾堡组织

标题

那个伊利亚特的荷马

作者

本垒打

翻译器

安德鲁郎

米一个

沃尔特叶子

一点点

和欧内斯特迈尔斯

米一个

发布日期

一月

电子书

发布日期

二月

语言

英语

..........

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>

#define SIZE 256

int end_line(FILE *file, int c)
{
int endLine = (c == '\r' || c == '\n');

if (c == '\r')
{
c = getc(file);
if (c != '\n' && c != EOF)
ungetc(c, file);
}

return endLine;
}

int get_word(FILE *file, char *word, size_t wordSize)
{
size_t i = 0;
int c;

//skip non-alpha characters
while ((c=fgetc(file)) != EOF && !isalpha(c) && isspace(c)){
; //do nothing
}

if (c != EOF)
word[i++] = c;

//read up to the next non-alpha character and store it to word
while ((c=fgetc(file)) != EOF && i < (wordSize - 1) && isalpha(c) && !end_line(file, c))
{
c=tolower(c);
word[i++] = c;
}
word[i] = 0;
return c != EOF;

}

//Main Function
int main (int argc, char **argv)
{
char *input = argv[1];
FILE *input_file;
char word[SIZE];

input_file = fopen(input, "r");

if (input_file == 0)
{
//fopen returns 0, the NULL pointer, on failure
perror("Canot open input file\n");
exit(-1);
}
else
{
while (get_word(input_file, word, sizeof(word)))
{
//do something with word;
printf("%s\n", word);
}
}

fclose(input_file);

return 0;
}

最佳答案

printf("%s\n", word); 行中,\n 是一个转义序列,表示一个换行符。这就是换行符的来源!

至于标点符号后跟空格时的额外换行,仔细看这里:

//skip non-alpha characters
while ((c=fgetc(file)) != EOF && !isalpha(c) && isspace(c)){

注释与代码不符,值得怀疑。 while() 测试内部发生了这么多事情也很可疑。编写如此简洁的代码毫无意义,只会让调试变得更加困难。不管出于什么原因,一些 C 程序员喜欢编写不可读的代码……但不要模仿他们。 :)

关于c - 如何摆脱单词之间的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18095554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com