用户输入值,但打印到屏幕的任意值。打印值与输入的值不匹配
User Inputs Value, but Arbitrary Value Printed to Screen. Printed Value doesn't Match Entered Value
#include<iostream>
#include<string>
using namespace std;
//class definition
class BankCustomer
{
public:
BankCustomer(); //constructor for BankCust class
void fullname(string, string);
string firstname();
string lastname();
bool setsocial(int s); //accept a arg. of int type
int getsocial();
private:
string fname, lname;
int SSNlength; //can't be changed by client; sensitive info should be made private
};
//class implementation
BankCustomer::BankCustomer(){}
void BankCustomer::fullname(string f, string l)
{
fname=f;
lname=l;
}
string BankCustomer::firstname()
{
return fname;
}
string BankCustomer::lastname()
{
return lname;
}
bool BankCustomer::setsocial(int s)
{
int count, SSNlength;
while(s != 0)
{
s /=10; //counts number of integers; count goes to max of ten
++count;
if(count == 9)
{
cout <<"nValid SSN Entered!" << endl;
SSNlength=s;
return true;
}
}
}
int BankCustomer::getsocial()
{
return SSNlength;
}
//client program
int main()
{
BankCustomer customer; //customer declared as object of BankCust class
string firstname, lastname;
int ssn, s;
//data assignment
cout <<"n Enter First Namen" << endl;
cin >> firstname;
cout<<"n Enter Last Namen"<< endl;
cin >> lastname;
customer.fullname(firstname,lastname);
do
{
cout<<"nEnter 9-Digit SSN"<< endl;
cin >> ssn;
}
while(!customer.setsocial(ssn)); //function will repeat as long as entered user ssn forces social() to evaluate it as false
//data ouput
cout <<"nFirst Name: "<<customer.firstname()<<"n"<< endl;
cout <<"nLast Name: "<<customer.lastname()<<"n"<< endl;
cout <<"n SSN is: "<<customer.getsocial()<<"n" << endl; //not printing correct value
}
当我运行程序时,输入的用户名和姓被正确地打印到屏幕上。但是,当我尝试打印输入的SSN值时,程序返回一个与用户输入的值不匹配的垃圾值。customer.getsocial()
返回值打印到cout<<"n SSN is:
行出现问题
您的成员变量SSNlength未初始化,而您在setsocial(int s)中定义了一个同名的本地变量
int count, SSNlength;
因此,你的成员变量不会被初始化,因为你的局部变量隐藏了它,这意味着getsocial()将总是返回垃圾…
此外,如果输入s无效,则应该从setsocial(int s)返回false,以避免未定义行为。比如bool BankCustomer::setsocial(int s)
{
SSNlength = s;
int count;
while(s != 0)
{
s /=10;
++count;
if(count == 9)
{
cout <<"nValid SSN Entered!" << endl;
return true;
}
}
return false;
}
相关文章:
- 打印时有二叉树问题.用户输入不打印任何内容
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 我要求用户输入大小和数组,但是当我打印矢量时,它仅显示'0'作为输出
- 如何打印不带空格的输入整数?
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 使用用户输入打印 6X10 矩阵的代码 - C++
- 如何使用打印到 PDF 打印机在 MFC 和 CView 中以编程方式打印而不提示输入文件名?
- 如何打印输入值
- 带有用户输入的C 文本数组,然后打印输入
- 读取和打印输入和 C 字符串C++
- 如何打印输入而不将其存储在c++中
- SFML—创建游标并打印输入
- c++的新功能,scanf不能正确读取/打印输入
- 如何打印输入的第一个数字?
- 如何自动打印输入的c++函数参数值
- C++:为什么 getline() 不打印输入字符串的最后一个单词?
- 打印输入的最小数字(不包括任何负数)
- 创建一个控制台应用程序,打开TCP/IP连接并用C++、C#或Java打印输入的字符串
- 从文件打印输入数据
- 按倒序打印输入字符串