1.请看下面两个计算空格和换行符数目的代码片段:
// Version 1
while (cin.get(ch)) // quit on eof
{
if (ch = ' ')
spaces++;
if (ch = '\n')
newlines++;
}
// Version 2
while (cin.get(ch)) // quit on eof
{
if (ch = ' ')
spaces++;
else if (ch ='\n')
newlines++;
}
第二种格式比第一种格式好在哪里呢?
答:这两种方法结果一样,但第二种方法即 if else 方法效率更高;比如,当 ch 为空格时,版本1对spaces++,然后看它是否为换行符,这将浪费时间,因为程序已经知道 ch 为空格,因此它不会是换行符,在这种情况下,版本2不会再次查看该字符是否为换行符。
2,在程序清单6.2中,用ch+1替换++ch将发生什么情况呢?
答:应该是会将字母强行转换成数字吧(我看下我敲的代码),没有说错,但书面语言表达为:按类型运算规则,ch+1的类型是int型,因此输出的是数值而非字符
3,请认真考虑下面的程序
#include<iostream>
using namespace std;
int main()
{
char ch;
int ct1, ct2;
ct1 = ct2 = 0;
while ((ch = cin.get()) != '$')
{
cout << ch;
ct1++;
if (ch = '$')
ct2