while (cin && cin.get() != '\n') continue;

在c++的学习中,经常遇到下面这段代码:

while (cin && cin.get() != '\n')
			continue;

作用

这段代码常常跟在输入之后,作用是过滤掉换行符。例如下面这段代码:

String sayings[ArSize];
	char temp[MaxLen];
	int i;
	for (i = 0; i < ArSize; i++) {
		cout << i + 1 << ": ";
		cin.get(temp, MaxLen);
		while (cin && cin.get() != '\n') //滤掉换行符
			continue;
		if (!cin || temp[0] == '\0') 
			break;
		else 
			sayings[i] = temp;
	}
	int total = i;
	cout << "Here are your sayings:\n";
	for (i = 0; i < total; i++)
		cout << sayings[i][0] << ": " << sayings[i] << endl;

上述代码的输出如下图:
正确输出
若删除while (cin && cin.get() != ‘\n’) continue;这两行,当键入’hi,‘并回车时,程序就会自动结束,输出结果如下:
错误输出
上述代码要求用户输入多个字符串,而用户输入时,作为每个字符串的结束,必然会输入换行符。若不过滤掉换行符,用户输入第一个字符串后的换行符,会被自动认为是第二个输入,这是就会触发temp[0]==’\0’条件,从而跳出for循环。而用while (cin && cin.get() != ‘\n’) continue;过滤掉换行符,就可以避免这种情况。

具体执行过程:

while (cin && cin.get() != '\n')
			continue;

cin.get()取得输入的字符,如果这个字符不是换行符,那么返回值为1,执行continue,即回到while继续这么干,若执行遇到换行符,则退出整个while循环,这个换行符弃之不顾。那么这整个语句的作用,就是读取该行换行符前的所有字符。

  • 11
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值