cin>>循環跳出問題
1.循環輸入數值cin>>num
int num;
vector<int> vec;
while(cin>>num){
vec.push_back(num);
}
for(auto a:vec)
cout<<a<<" "<<endl;
-
以非空格作爲num的開始,以遇到的第一個空格作爲num的結束,因此輸入的時候只要數值之間以空格隔開即可,無論幾個空格都可以;
-
回車的作用:每按下一次回車鍵,輸入的數據就會被輸入緩衝區,此時會檢查緩衝區中有無結束符
\n
和非法字符(任何字母)的存在,如果存在,則退出循環,且結束符和非法字符之後的數據不會被循環體處理;Input: 1 2 3\n 4 5 6 The results are: 1 2 3
Input: 1 2 3m n 4 5 6 The results are: 1 2 3
-
另一種退出循環的方式是
CTRL+D
,實驗結果:-
回車
+CTRL+D
:直接退出循環;Input: 1 2 3 4 The results are: 1 2 3 4
-
CTRL+D
+CTRL+D
:直接退出循環;Input: 1 2 3 4 The results are: 1 2 3 4
-
2.循環輸入字符串cin>>str
- 以非空格作爲str的開始,以遇到的第一個空格作爲str的結束,因此輸入的時候只要字符串之間以空格隔開即可,無論幾個空格都可以;
string str;
list<string> l;
cout<<"Input:"<<endl;
while(cin>>str){
l.push_back(str);
}
cout<<endl<<"The results are:"<<endl;
for(auto a:l)
cout<<a<<" "<<endl;
回車
+CTRL+D
:直接退出循環;CTRL+D
+CTRL+D
:直接退出循環;- 結束符
\n
無效,會被作爲字符串處理
Input:
a b c d e
The results are:
a
b
c
d
e
getline()循環跳出
string s;
list<string> l1;
cout<<"Input:"<<endl;
while(getline(cin,s))
l1.push_back(s);
cout<<endl<<"The results:"<<endl;
for(auto a:l1)
cout<<a<<endl;
- 此時,不再以空格作爲一個字符串的結束,而是把一整行作爲一個字符串
Input:
a b c d
e f g
hi j k
The results:
a b c d
e f g
hi j k
回車
+CTRL+D
:直接退出循環;CTRL+D
+CTRL+D
:直接退出循環;- 結束符
\n
無效,會被作爲字符串處理