|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- /*
- 时间:2013年3月26日14:41:19
- 程序功能:统计输入的字符、单词和行
- */
- #include <stdio.h>
- #include <stdbool.h> //为isspace()提供函数原型
- #include <ctype.h> //为bool、true和false提供宏定义
- #define STOP '|'
- int main(void)
- {
- char c; //读入字符
- char prev; //前一个读入字符
- long n_chars = 0L; //字符数
- int n_lines = 0; //行数
- int n_words = 0; //单词数
- int p_lines = 0; //不完整的行数
- bool inword = false;
- printf("Enter text to be analyzed (| to terminate): \n");
- prev = '\n'; //用于识别完整的行
- while ((c = getchar()) != STOP)
- {
- n_chars++; //统计字符
- if (c == '\n')
- n_lines++; //统计行
- if (!isspace && !inword)
- {
- inword = true; //开始一个新单词
- n_words++; //统计单词
- }
- if (isspace || inword)
- inword = false; //到达单词的结尾
- prev = c;
- }
- if (prev != '\n')
- p_lines = 1;
- printf("characters = %ld, words = %d, lines = %d,",
- n_chars, n_words, n_lines);
- printf("partial lines = %d\n", p_lines);
- return 0;
- }
复制代码
C语言“统计字符、单词和行”问题中,实现统计单词出错。上面是源代码。
这个是在vim中运行的结果:
和预期的结果不一样,characters = 55, words = 0, lines = 3,partial lines = 0
characters = 55得到了正确的结果,lines = 3得到了正确的结果,partial lines = 0得到了正确的结果,但是在统计单词words的时候却运行不正确!???请问这是为什么?哪里出问题了吗?
上面是vim中的运行结果和源代码。下面也在VC++6.0中测试了下:
因为在VC++6.0中用isspace()函数编译的时候出错,所以我把代码改成了这样:
- /*
- 时间:2013年3月26日14:41:19
- 程序功能:统计输入的字符、单词和行
- */
- #include <stdio.h>
- //#include <stdbool.h> //为isspace()提供函数原型
- #include <ctype.h> //为bool、true和false提供宏定义
- #define STOP '|'
- int main(void)
- {
- char c; //读入字符
- char prev; //前一个读入字符
- long n_chars = 0L; //字符数
- int n_lines = 0; //行数
- int n_words = 0; //单词数
- int p_lines = 0; //不完整的行数
- bool inword = false;
- printf("Enter text to be analyzed (| to terminate): \n");
- prev = '\n'; //用于识别完整的行
- while ((c = getchar()) != STOP)
- {
- n_chars++; //统计字符
- if (c == '\n')
- n_lines++; //统计行
- if (c != ' ' && c != '\n' && c != '\t')
- {
- inword = true; //开始一个新单词
- n_words++; //统计单词
- }
- if (c == ' ' || c == '\n' || c == '\t')
- inword = false; //到达单词的结尾
- prev = c;
- }
- if (prev != '\n')
- p_lines = 1;
- printf("characters = %ld, words = %d, lines = %d,",
- n_chars, n_words, n_lines);
- printf("partial lines = %d\n", p_lines);
- return 0;
- }
复制代码 在VC++6.0中运行的结果是这样的:
这里也是统计单词的时候没有运行正确!!
并且words统计的时候统计了字符的个数,而不是单词!请问这个又是哪里错了?
统计单词我的思路是这样的,讲一个单词定义为不包含空白字符(也就是说,没有空格,制表符或换行符)的一系列字符。因此,“dtz”和“asdasd”是单词。一个单词以程序首次遇到非空白符开始,在下一个空白符出现时结束。检测非空白符最简单了的判断表达式是这样的:
- c != ' ' && c != '\n' && c != '\t'
复制代码 检测空白字符最简单明了的判断是:
- c == ' ' || c == '\n' || c == '\t'
复制代码
这个可以用ctype.h文件中的isspace()函数来解决。如果该函数的参数是空白字符,它就返回真。因此如果是c是空白字符,isspace为真;而如果c不是空白字符,!isspace为真。
之前说过,因为VC++6.0中用isspace函数时错误,所以改用了比较复杂的公式c != ' ' && c != '\n' && c != '\t'和c == ' ' || c == '\n' || c == '\t'来代替isspace,并在vim中用isspace代替比较复杂的公式运行。两个运行结果都和预期不一样,并且出现了不一样的结果。
请问这个是什么问题导致的?
这个程序错了吗?
我觉得思路是没有错的,因为这是CPP书上的,
如果错了要怎么写才能实现统计单词? |
|
|