见见这个代码 为什么输入q是好的 但是输入5 -5 再输入q就是错的
看看这个代码 为什么输入q是好的 但是输入5 -5 再输入q就是错的
#include <iostream>
double hmean(double x, double y);
void what(double & x,double & y);
class error{};
int main()
{
using namespace std;
double x, y, z;
cout << "please enter two number : ";
while(cin.peek() != 'q' && cin.peek() != 'Q')
{
try{
what(x,y);
z = hmean(x,y);
}
catch(error)
{
cout << "input should be number \n";
cout << "enter another two number : ";
cin.clear();
cin.sync();
cout << "enter another two number : ";
continue;
}
catch(char* s)
{
cout << s <<endl;
cin.clear();
cin.sync();
cout << "enter another two number : ";
continue;
}
cout << "the hmean of " << x << " and " << y << " is " << z << endl;
cout << "enter another two number : ";
cin.clear();
cin.sync();
}
cin >> x;
cout <<"BYe" <<endl;
cin.get();
cin.get();
return 0;
}
void what(double & x, double & y) //检验是有输入的是数字
{
if(!(std::cin >> x >> y))
throw error();
}
double hmean(double x,double y)//检验是否互为倒数
{
double z;
if(x == -y)
throw "the negative is not hmean";
else
z=1/(x+y);
return z;
}
------解决思路----------------------
乍看起来c++的cin、cout在输入、输出上比c的scanf、printf简单,不用格式控制符!
但是不用格式控制符,输入输出恰好是你期望的格式的时候好说;等到输入输出不是你期望的格式的时候,你就会觉得还是用格式控制符更方便、更靠谱。
摒弃cin、cout!
使用scanf、printf。
#include <iostream>
double hmean(double x, double y);
void what(double & x,double & y);
class error{};
int main()
{
using namespace std;
double x, y, z;
cout << "please enter two number : ";
while(cin.peek() != 'q' && cin.peek() != 'Q')
{
try{
what(x,y);
z = hmean(x,y);
}
catch(error)
{
cout << "input should be number \n";
cout << "enter another two number : ";
cin.clear();
cin.sync();
cout << "enter another two number : ";
continue;
}
catch(char* s)
{
cout << s <<endl;
cin.clear();
cin.sync();
cout << "enter another two number : ";
continue;
}
cout << "the hmean of " << x << " and " << y << " is " << z << endl;
cout << "enter another two number : ";
cin.clear();
cin.sync();
}
cin >> x;
cout <<"BYe" <<endl;
cin.get();
cin.get();
return 0;
}
void what(double & x, double & y) //检验是有输入的是数字
{
if(!(std::cin >> x >> y))
throw error();
}
double hmean(double x,double y)//检验是否互为倒数
{
double z;
if(x == -y)
throw "the negative is not hmean";
else
z=1/(x+y);
return z;
}
------解决思路----------------------
乍看起来c++的cin、cout在输入、输出上比c的scanf、printf简单,不用格式控制符!
但是不用格式控制符,输入输出恰好是你期望的格式的时候好说;等到输入输出不是你期望的格式的时候,你就会觉得还是用格式控制符更方便、更靠谱。
摒弃cin、cout!
使用scanf、printf。
#include <stdio.h>
int main()
{
int a,b,n,v,r,k;
char buf[80];
char *p;
k=0;
r=EOF;
while (1) {
if (EOF==r) {
fgets(buf,80,stdin);
p=buf;
}
while (1) {
r=sscanf(p,"%d%n",&v,&n);
if (1==r) {k++;break;}
if (EOF==r) break;
p++;
}
if (EOF==r) continue;
p+=n;
if (1==k) a=v;
if (2==k) {
b=v;
break;
}
}
printf("%d,%d\n",a,b);
return 0;
}