以下の作り方がわかりません。一連の数字を入力し、0 を入力すると、cin を停止し (Enter をクリックしたように)、別の行にある (number%2==0) の数字のみを自動的にカウントしたいと考えています。関数で行うことは可能ですか?あなたが私を理解してくれることを願っています:)
たとえば、123456785435430 と入力しています (「0」を入力したので、cin はすぐに停止し、2 4 6 8 4 4 3 を計算します)。
これは、特定の区切り文字で機能する単純なバージョンです。
#include <iostream>
using namespace std;
string input_until_delimiter (char delimiter)
{
string buffer = new string ();
char c = delimiter;
while ((c = get()) != delimiter) buffer += c;
return buffer;
}
これに沿って何かが必要になります:
char x;
std::vector<int> evens;
do {
std::cin.get(x);
int v = x - '0'; // int value
if (v % 2 == 0 and v != 0)
evens.push_back(v);
} while (x != '0');
for (std::vector<int>::iterator it = evens.begin(); it != evens.end(); ++it)
std::cout << (*it) << " ";
演習用のバージョンは次のとおりです。
#include <vector>
#include <iostream>
void brc() {
int x;
std::cin >> x;
if (x == 0) return;
if (x % 2 == 0)
std::cout << x << " ";
brc();
}
int main() {
brc();
return 0;
}