用户输入值,但打印到屏幕的任意值。打印值与输入的值不匹配

User Inputs Value, but Arbitrary Value Printed to Screen. Printed Value doesn't Match Entered Value

本文关键字:打印 输入 任意值 不匹配 用户 屏幕      更新时间:2023-10-16
#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;
}