|
初學者通常面對已知數量的輸入法比較沒問題,例如下面兩個範例。 以下範例輸入的數字以空白或 Enter 隔開。 範例一、已知輸入 6 個整數 ... 範例二、已知輸入一串整數,最後一整數以 0 結尾。(0 表示停止輸入) 下面範例輸入數字的數量未知且不知何時停止輸入。 範例:輸入一串自然數列,如果是偶數則輸出,若無偶數,輸出 No。(至少輸入一數) 以空白當數字間的間格 輸入測試 1 :7 13 6 8 9 4 結果:6 8 4 輸入測試 2 :12 3 6 7 11 結果:12 6 輸入測試 3 :79 結果:No 程式碼:(使用 getchar 抓 空白 與 Enter)
#include <iostream>
using namespace std;
int main() {
char c;
int x;
bool t = false;//偶數旗標
while(1) {
cin >> x;
if( x%2 == 0 ){
cout << x << ' ';
t = true;
}
c=getchar();//接收數字後的空白或 Enter
if(c == '\n') break;//如果是 Enter 表示結束
}
if(t == false) cout << "No\n";//是偶數則設為 true
return 0;
}
另一種使用 strtok 字串分割方法
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main() {
string s;
char *p;
int x;
bool t = false;//偶數旗標
getline(cin , s);
p = strtok((char *)s.c_str() , " ");//依據空白分割
do{
x = atoi(p);//string 轉型 int
if( x%2 == 0 ){
cout << x << '\n';
t = true;//是偶數則設為 true
}
p = strtok(NULL," ");//繼續分割下一個數字
}while(p!=NULL);//分割完後,strtok 傳回 NULL
if(t == false) cout << "No\n";
return 0;
}
以跳行當數字間的間格輸入測試 1 : 7 13 6 8 9 4 結果: 6 8 4 輸入測試 2 : 12 3 6 7 11 結果: 12 6 輸入測試 3 : 79 結果:No 程式碼:(使用 getline 及轉型)
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
string s;
int x;
bool t = false;//偶數旗標
while(1) {
getline(cin , s);
if(s == "") break;
x = atoi(s.c_str());//string 轉型 int
if( x%2 == 0 ){
cout << x << '\n';
t = true;//是偶數則設為 true
}
}
if(t == false) cout << "No\n";
return 0;
}
|