热点推荐:ASP.Net | ADO.Net | VB.Net | Web服务器 | Access | MSSQL | MySQL | Oracle | .Net控件 | Win 9x | Win 2000 | Win 2003 | DOS | Unix | 注册表 | 应用其它 | 安装调试 | 基本操作 | 使用技巧 | 系统优化 |故障处理 | 个性风格 | 病毒安全 | 专杀工具
您现在的位置: 中华IT技术网 >> FAQ >> C/C++ >> C语言 >> 正文
全文
cin读入数值的问题
作者:1024k    文章来源:Web    更新时间:2007-6-15

#include "iostream.h"
void main()
{
    int password=1234;
    int get_pass=0;
    while(get_pass!=password)
    {
        cout << "Please Enter Password:";
        cin >> get_pass;
    }
}
执行是如果输入数字以外的符号,则会形成输出cout语句的死循环。
cin是怎样读取数据的。
---------------------------------------------------------------

当用cin和scanf等读入数值,但输入的却是字符时,发生问题比较难解决,我建议不要去研究它了,也没什么意义。其实,对于数据输入,如果想使程序的健壮性好,最好是先读入字符串,然后自己解析,碰到不合法字符提示错误。
---------------------------------------------------------------

应该这样:
#include "iostream.h"

void main()
{
    int password=1234;
    int get_pass=0;
    while(get_pass!=password)
    {
        cout << "Please Enter Password:";
        cin >> get_pass;
if (!cin.good())
{
cin.clear();
cin.ignore();
}
    }
}

---------------------------------------------------------------

不要用cin >>,改成如下:
const int MAX = 200;
char get_pass[MAX];
while(strcmp(get_pass,atoi(password))
{
        cout << "Please Enter Password:";
        cin.getline(get_pass,MAX);
}

---------------------------------------------------------------

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

void main()

  char *password="1234";
  char get_pass[5]; 
  while (strcmp((char *)get_pass, password))
  { 
    cout<<"Please Enter Password:"; 
    cin>>setw(5)>>get_pass;
    cin.seekg(ios::end);
  }
}

-------------
以上程序在VC6下测试通过.
---------------------------------------------------------------

#include <iostream>
#include <string>
void main()
{
using namespace std;
    int password=1234;
    int get_pass=0;
    while(get_pass!=password)
    {
        cout << "Please Enter Password:";
        cin >> get_pass;
if(!cin && !cin.eof())
{
cin.clear();
string s;
cin >> s;
}
    }
}
//test:
//Please Enter Password:hello
//Please Enter Password:wolrd
//Please Enter Password:1234
//Press any key to continue
---------------------------------------------------------------

if (!cin.good())
{
     cin.clear();
     char ps[80] ;
     cin.getline(ps,80);
     continue;
}

相关文章
最新更新
编辑推荐
热门图片
频道大全
文章阅读排行
周排行
月排行