#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;
}