C++ while(cin>>a) cin输入直到回车结束
生活随笔
收集整理的這篇文章主要介紹了
C++ while(cin>>a) cin输入直到回车结束
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
經(jīng)常遇到循環(huán)輸入,直到符合某種條件時結(jié)束輸入。
cin>>s是有返回值的,只要s滿足類型條件,就會return true,一直執(zhí)行下去,而cin會忽略空格或者enter,因此,enter后不會結(jié)束循環(huán)。只能ctrl+Z。
其實(shí)很簡單:通過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]<<" "; }這里再以創(chuàng)建鏈表舉一個例子:
#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; }運(yùn)行結(jié)果:
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的C++ while(cin>>a) cin输入直到回车结束的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新手坐高铁怎么找车厢_一个新手怎么做直播
- 下一篇: 打印机乱码不停打印_关于东芝复合机连接打