cin
является моделью std::istream
. При любом исходе результат stream >> x
является ссылкой на сам istream
.
istream
содержит несколько флагов, указывающих на успех или неудачу предыдущих операций.
istream
также конвертируется в bool
. Значение bool будет true
, если предыдущие операции были успешными и false в противном случае (по какой-либо причине).
Таким образом, если мы желаем, мы можем связать не только операции >>
, но и другие проверки.
Это может быть немного продвинутым, но я думаю, вы найдете это интересным. Вы можете скомпилировать и запустить эту программу как есть.
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
struct success_marker
{
success_marker(bool& b)
: _bool_to_mark(std::addressof(b))
{}
void mark(bool value) const {
*_bool_to_mark = value;
}
bool* _bool_to_mark;
};
std::istream& operator>>(std::istream& is, success_marker marker)
{
marker.mark(bool(is));
return is;
}
success_marker mark_success(bool& b) {
return success_marker(b);
}
void test(const std::string& test_name, std::istream& input)
{
bool have_a = false, have_b = false;
std::string a, b;
input >> std::quoted(a) >> mark_success(have_a) >> std::quoted(b) >> mark_success(have_b);
std::cout << test_name << std::endl;
std::cout << std::string(test_name.length(), '=') << std::endl;
std::cout << have_a << " : " << a << std::endl;
std::cout << have_b << " : " << b << std::endl;
std::cout << std::endl;
}
int main()
{
std::istringstream input("\"we have an a but no b\"");
test("just a", input);
// reset any error state so the stream can be re-used
// for another test
input.clear();
// put new data in the stream
input.str("\"the cat sat on\" \"the splendid mat\"");
// test again
test("both a and b", input);
return 0;
}
ожидается выход:
just a
======
1 : we have an a but no b
0 :
both a and b
============
1 : the cat sat on
1 : the splendid mat
Почему вы говорите, «Так у меня есть следующая проблема» в каждом из ваших вопросов? Как это относится к любому из вопросов? –