经常遇到循环输入,直到符合某种条件时结束输入。

cin>>s是有返回值的,只要s满足类型条件,就会return true,一直执行下去,而cin会忽略空格或者enter,因此,enter后不会结束循环。只能ctrl+Z。

其实很简单:通过get()判断下一个输入是不是回车就行。

while(cin>>a){
    ...
    if(cin.get()=='\n') break;
} 

举个例子:

#include <bits/stdc++.h>
using namespace std;
 
int b[10];
int main() 
{
	int i=0,a;
	while(cin>>a){
		b[i++]=a;
    	if(cin.get()=='\n') break;	
	} 
	for(i=0;i<10;i++) cout<<b[i]<<" ";
}

这里再以创建链表举一个例子:

#include <bits/stdc++.h>
using namespace std;

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
	
};

int main()
{
	ListNode* head1 = new ListNode(NULL);
	ListNode* head = new ListNode(NULL);
	head1 = head;
	int a;
	while (cin >> a) {
		ListNode* tmp = new ListNode(a);
		head->next = tmp;
		head = tmp;
		if (cin.get() == '\n') break;
	}
	while (head1->next != NULL) {
		cout << head1->next->val<<endl;
		head1 = head1->next;
	}
	system("pause");
	return 0;
}

运行结果: