我的程序:从用户那里获取有关个人详细信息的输入,然后输出信息。
我的问题:程序无法计算位数作为电话号码字段的输入。它接受超过10位数作为电话号码的输入。
我的目标:检查“电话号码”的输入,并确保该号码为10位数。
我的代码:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
class Personal_Details
{
public:
void setFirstName (string newFirstName);
void setLastName (string newLastName);
void setBirthdate (int newBirthday);
void setEMail (string newEMail);
void setPhoneNumber (int newPhoneNumber);
void QUESTIONS();
string getFirstName();
string getLastName();
string getEMail();
int getPhoneNumber();
int getBirthdate();
private:
string FirstName;
string LastName;
string EMail;
int PhoneNumber;
int Birthdate;
};
void Personal_Details :: setFirstName (string newFirstName)
{
FirstName = newFirstName;
}
void Personal_Details :: setLastName (string newLastName)
{
LastName = newLastName;
}
void Personal_Details :: setBirthdate (int newBirthdate)
{
Birthdate = newBirthdate;
}
void Personal_Details :: setEMail (string newEMail)
{
EMail = newEMail;
}
void Personal_Details :: setPhoneNumber (int newPhoneNumber)
{
PhoneNumber = newPhoneNumber;
}
string Personal_Details :: getFirstName()
{
return FirstName;
}
string Personal_Details :: getLastName()
{
return LastName;
}
int Personal_Details :: getBirthdate()
{
return Birthdate;
}
string Personal_Details :: getEMail()
{
return EMail;
}
int Personal_Details :: getPhoneNumber()
{
if (PhoneNumber>12)
{
cout <<"INVALID. Program will now close.";
}
system ("PAUSE");
return PhoneNumber;
}
void Personal_Details :: QUESTIONS()
{
cout << "A.) Enter the following details:-" << endl <<endl;
cout << "First Name: ";
getline (cin, FirstName);
cout << endl;
cout << "Last (Family) Name: ";
getline (cin, LastName);
cout << endl;
cout << "Birthdate: ";
cin >> Birthdate;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "Email Address: ";
getline (cin, EMail);
cout << endl;
cout << "Phone Number: ";
cin >> PhoneNumber;
cout << endl;
cout<< FirstName <<" "<< LastName << endl
<<"Birthdate: "<< Birthdate << endl
<<"Email ID: "<< EMail << endl
<<"Phone Number: "<< PhoneNumber << endl;
}
int main()
{
Personal_Details NewContact;
cout << "- Add New Contact Information -" << endl << endl;
cout << "Note: Please type in only intergers (numbers) for 'Birthdate' and 'Phone Number' field. Also, phone number should be less than/or equal to 10 digits." << endl;
cout << "Else, this program will terminate abruptly." << endl << endl;
NewContact.QUESTIONS();
cout << endl << endl;
cout << "Press Any Key to Exit.";
cin.ignore();
cin.get();
return 0;
}
请您查看并检查我无法输入真正的10位数电话号码的原因?我是C ++的新手,所以我无法找到解决方案。谢谢你的帮助!
答案 0 :(得分:7)
您将电话号码存储为int,但整数范围为-2,147,483,648至2,147,483,647;输入超出该范围的10位数字会导致溢出,可能会导致程序崩溃。
您可能希望将电话号码作为字符串读取,检查每个字符的有效性,然后根据需要进行处理(例如:区号的变量,7位数的变量,拒绝超出范围输入并重新提示)。