注册 登录
编程论坛 C++教室

C++怎么解决类型输入不匹配问题?

outsider_scu 发布于 2010-11-17 22:07, 711 次点击
例如:
程序代码:
#include<iostream>
using namespace std;
int main()
{
    int a,b;
    while(1)
    {
       cin>>a>>b;
       cout<<a<<b<<endl;
       if(a==b) break;
    }
    system("pause");
    return 0;
}

上面这段程序,如果输入字符'a',就进入死循环了。
这样的问题不是致命的么?怎么解决啊??
7 回复
#2
m21wo2010-11-17 22:30
当你输入 a 时,编译器就知道你输入错误不是整形,就会丢弃,按回车,就不在执行输入b了,同时分配 给a,b赋值,在我的编译器都是-858993460,故a=b,跳出循环!!执行完!
 
输入之后 可以用
程序代码:
#include<iostream>
using namespace std;
int main()
{
    int a,b;
    while(1)
    {
s:      cin>>a;
        if(cin.fail())
        {
            cin.clear();
            cin.ignore();
            goto s;
        }
        cin>>b;
        cout<<a<<b<<endl;
        if(a==b) break;
    }
    system("pause");
    return 0;
}

 
#3
outsider_scu2010-11-17 22:46
还有更体面的解决方式吗?难到每个输入都要这么处理,还要用GOTO?
#4
lintaoyn2010-11-18 08:33
程序代码:
#include<iostream>
using namespace std;
int main()
{
    int a,b;
    while(1)
    {
       cin>>a>>b;
       if(cin.fail()){ cerr << "input error";break;}
       cout<<a<<b<<endl;
       if(a==b) break;
    }
    system("pause");
    return 0;
}

cin.fail() 检测是否出现错误的输入格式。
#5
lintaoyn2010-11-18 08:59
程序代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string buf;
    int a,b;
    while(1)
    {
      
      while(!(cin >> a >> b))
      {//还可以提示出现输入错误
          cin.clear();//使流能用。
          cin >> buf;//将错误的字符全部排尽。
      }
       cout<<a<<b<<endl;
       if(a==b) break;
    }
    system("pause");
    return 0;
}

这样能体面点。
#6
outsider_scu2010-11-18 13:45
程序代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
    int a,b;
    while(1)
    {
      
      while(!(cin >> a >> b))
      {//还可以提示出现输入错误
          cout<<"input error"<<endl;
          cin.clear();//使流能用。
          cin.ignore(100,'\n');
      }
       cout<<a<<b<<endl;
       if(a==b) break;
    }
    system("pause");
    return 0;
}

这样真的很体面。。。
谢了。。。
体会很深。。。
#7
只手驾破船2010-11-18 17:08
写得好啊,我还没学到这里,学习了
#8
VenusNefu2010-11-24 12:33
perfect 受用
1