#include <iostream>
using namespace std;
const int arSize = 20; // 最长输入字符为19个,留出一个给‘\0’,作为字符串结束标志。
void strcount(const char*);
int main(int argc, char* argv[]) {
char input[arSize];
char next;
cout << "Enter a line: ";
cin.get(input, arSize); // 读入最多arSize-1个字符到input中,并在input的最后添加'\0'。
// 但是回车符留在输入缓冲区中。
while (!cin.fail()) { // 如果输入为空,则cin.fail()返回true,否则为true。
cin.get(next); // 读入下一个字符,也即从上一次输入通过cin.get(input, arSize)
// 后,留在输入缓冲区中的字符序列读取。
while (next != '\n') { // 上次用户输入分两种情况:
// 1)输入字符序列长度(不包括回车)小于或等于arSize-1,那么
// 这时输入缓冲区中只有‘\n',也就是回车符,cin.get(next)语
// 句读取这个字符,并且跳过当前while语句。
cin.get(next); // 2)输入字符序列大于arSize,那么输入缓冲区中将保留除已保存
// 到input中余下的字符(包括回车).这时,next的值为非回
// 车,那么就进入到这个内层的while循环中,然后不断从缓冲
// 区中读字符到next,不做处理,直到遇到'\n'才跳出内循环。
}
strcount(input); // 将本次输入的字符串计数,累加到静态局部变量中
cout << "Enter a line: "; // 准备下一次输入
cin.get(input, arSize);
}
cout << "Bye!\n";
return 0;
}
void strcount(const char* str) {
static int total = 0;
int count = 0;
cout << "\"" << str << "\" constains: ";
while (*str++) { // or while(*str) { str++; count++;}
count++;
};
total += count;
cout<< count << " letters." << endl;
cout << "Now the total number of letters that have been inputed: " << total << endl;
}
从命令行循环读入整行字符串,然后计算输入的总字符个数。演示了cin.get()函数的用法细节。