cin.get()函数循环读入整行

#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()函数的用法细节。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值