#include <stdlib.h>
#include <stdio.h>
int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;
char lastch = -1;
c = 0;
line = 0;
word = 0;
while((ch = getchar()) != EOF)
{
c ++;
if (ch == '\n')
{
line ++;
}
if (ch == ' ' || ch == '\n')
{
if (!(lastch == ' ' && ch == ' '))
{
word ++;
}
}
lastch = ch;
}
printf( "%lu %lu %lu\n", c, word, line );
return 0;
}
因此,该程序计算标准输入中的字符,行或单词的数量。但其中一个要求是由任何符号(如!, - ,+等)分隔的单词必须被视为2个单词。我如何修改我的代码呢?
答案 0 :(得分:1)
创建一个表示单词分隔的字符数组。 修改while循环中的第二个if条件,检查数组中是否存在ch,并且该数组中不存在lastch。
修改后的代码:
#include <stdlib.h>
#include <stdio.h>
int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;
char lastch = -1;
int A[256] = {0};
//Initialize the array indexes which are to be treated as separators.
//Next check the presence of any of these characters in the file.
A[' '] = 1; A['+'] = 1; A['!'] = 1; A['-'] = 1; A['\n'] = 1;
c = 0;
line = 0;
word = 0;
while((ch = getchar()) != EOF)
{
c ++;
if (ch == '\n')
{
line ++;
}
if (A[ch] == 1)
{
if (!(A[lastch] == 1 && A[ch] == 1))
{
word ++;
}
}
lastch = ch;
}
printf( "%lu %lu %lu\n", c, word, line );
return 0;
}
答案 1 :(得分:0)
只需按以下方式使用isalnum()函数
#include <stdlib.h>
#include <stdio.h>
int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;
char lastch = -1;
c = 0;
line = 0;
word = 0;
while((ch = getchar()) != EOF)
{
c ++;
if(ch=='\n')
{
line++;
continue;
}
if (!isalnum(ch))
{
word++;
}
}
printf( "%lu %lu %lu\n", c, word, line );
return 0;
}