C++ 如何编写一个while循环,该循环接受两个int并以'|';在c++;?
我正在写一本自学课本。我可以做while循环没有问题,但是我不知道如何做终止字符 以下是我现在拥有的:C++ 如何编写一个while循环,该循环接受两个int并以'|';在c++;?,c++,C++,我正在写一本自学课本。我可以做while循环没有问题,但是我不知道如何做终止字符 以下是我现在拥有的: #include "../../std_lib_facilities.h" // Supplied by book author int main() { int ii = 0; int yy = 0; bool test = true; cout << "Enter two ints" << endl; while (te
#include "../../std_lib_facilities.h" // Supplied by book author
int main()
{
int ii = 0;
int yy = 0;
bool test = true;
cout << "Enter two ints" << endl;
while (test)
{
cin>>ii, cin>>yy;
// this if statement doesn't work
if (ii == '|' || yy == '|')
{
test = false;
}
// this if statement catches all bad input, even the terminating '|'
if (cin.fail())
{
cout << "bad input";
cin.clear();
cin.ignore();
continue;
}
else
cout << ii << yy << endl;
}
return 0;
}
#包括“../../std_lib_facilities.h”//由书籍作者提供
int main()
{
int ii=0;
int-yy=0;
布尔检验=真;
coutⅡ,cin>>yy;
//这个if语句不起作用
如果(ii='|'| | yy=='|')
{
测试=假;
}
//此if语句捕获所有错误输入,甚至终止的“|”
if(cin.fail())
{
如果您不熟悉流,可能会有点困惑。这是一个需要更多研究的大主题。下面是一个应该有效的示例,希望能帮助您开始
int main(int argc, char* argv[])
{
bool test = true;
while ( test ) {
std::cout << "Enter two integers> ";
int x, y;
// if this fails, stream is bad.
// @note this will fail for any input which cannot be interpreted
// as an integer value.
if (std::cin >> x >> y) {
std::cout << x << " " << y << std::endl;
}
else {
// clear stream error state so we can read from it again.
std::cin.clear();
// check for terminating character; else unknown.
if (std::cin.get() == '|')
std::cout << "Terminator found, exiting." << std::endl;
else
std::cerr << "Error: bad input, exiting." << std::endl;
// in either case the loop terminates.
test = false;
}
}
return 0;
}
intmain(intargc,char*argv[])
{
布尔检验=真;
while(测试){
标准::cout>x>>y){
std::cout在输入两个数字之前,按如下所示使用cin.peek()
函数:
c=(cin >> ws).peek();
if(c=='|')
{
cout<<"exiting";return 1;
}
1.学习类型的概念-你不能将苹果和梨进行比较,也就是说,(ii==“|”)没有意义。2.学习缩进和大括号的使用。谢谢你,Ed。我刚刚尝试修复2。不确定如何处理1,但如果你有任何想法?@timEihajj-理解集合论
int main()
{
int ii = 0;
int yy = 0;
bool test = true;
cout << "Enter two ints" << endl;
while (test)
{
char c;
c=(cin >> ws).peek();
if(c=='|')
{
cout<<"exiting";return 1;
}
cin>>ii, cin>>yy;
if (cin.fail())
{
cout << "bad input";
cin.clear();
cin.ignore();
continue;
}
else
cout << ii << yy << endl;
}
return 0;
}