我是C语言和系统编程的初学者。为了一项作业任务,我需要编写一个程序从stdin读取输入,将其分解成单词并使用System V消息队列(例如计数单词)向排序子进程发送单词。我卡在输入部分。我正在尝试处理输入,删除非字母字符,将所有字母单词转换为小写,最后将一行单词拆分为多个单词。到目前为止,我可以打印所有小写字母单词,但是有单词之间的空行,我认为这是不正确的。请问有人能够看一下并给我一些建议吗?
文本文件中的示例:荷马的《伊利亚特》(The Iliad of Homer)项目古腾堡电子书。
我认为正确的输出应该是:
the
project
gutenberg
ebook
of
the
iliad
of
homer
by
homer
但是我的输出结果如下:
project
gutenberg
ebook
of
the
iliad
of
homer
<------There is a line there
by
homer
我认为空行是由","和"by"之间的空格引起的。我尝试过像“如果 isspace(c) 则什么也不做”这样的方法,但它没有起作用。我的代码如下。任何帮助或建议都将受到赞赏。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
//Main Function
int main (int argc, char **argv)
{
int c;
char *input = argv[1];
FILE *input_file;
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 ((c =fgetc(input_file)) != EOF )
{
//if it's an alpha, convert it to lower case
if (isalpha(c))
{
c = tolower(c);
putchar(c);
}
else if (isspace(c))
{
; //do nothing
}
else
{
c = '\n';
putchar(c);
}
}
}
fclose(input_file);
printf("\n");
return 0;
}
编辑**
我编辑了我的代码,最终得到了正确的输出:
int main (int argc, char **argv)
{
int c;
char *input = argv[1];
FILE *input_file;
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
{
int found_word = 0;
while ((c =fgetc(input_file)) != EOF )
{
//if it's an alpha, convert it to lower case
if (isalpha(c))
{
found_word = 1;
c = tolower(c);
putchar(c);
}
else {
if (found_word) {
putchar('\n');
found_word=0;
}
}
}
}
fclose(input_file);
printf("\n");
return 0;
}
perror(输入)
。没有文件名的错误消息是很糟糕的事情之一。 - William Pursell