C++ variable returns garbage value

Nigel 291 Reputation points
2023-05-08T11:15:58.8+00:00

I have created an app just to read person and client details. I have used an int for age, within a struct which works just fine. However I have created a long for mobile number within a class which ignores the value input and returns garbage. The Client.h file is shown below, Client.cpp just has #include "Client.h".

#pragma once

#include <string.h>

#include <iostream>

using namespace std;

class Client

{

public:

string firstname, lastName;

long mobile = 0;

};

The int Main() file contains the following:

//Client is a class created elsewhere in Client.h so we create an instance here a name it c.
    Client c;
    string name = "";
    long num = 0;

    //The details can then be entered for the client class
    cout << "\nPlease enter client details:" << endl;
    cout << "First name: ";
    cin >> c.firstname;
    cout << "Last name: ";
    cin >> c.lastName;
    cout << "Mobile phone: ";
    cin >> c.mobile;

    //before being converted into new variables for output (or storage)
    name = c.firstname + " " + c.lastName;
    num = c.mobile;

    //and displayed to the console.
    cout << "\nClient information: " << endl;
    cout << "\nName: " << name << endl;
    cout << "Mobile: " << num << endl;

    return 0;
When run, the app performs fine and outputs all the string based variables perfectly but the value of long num (the c.mobile value) is just garbage.  Any pointers to what I am doing wrong would be appreciated.  Thank you in advance.
Developer technologies | C++
Developer technologies | C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other
A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.
{count} votes

Answer accepted by question author
  1. Viorel 125.7K Reputation points
    2023-05-08T11:35:53.8166667+00:00

    Probably you entered a large or incorrect number. Long is 32-bit. Use long long mobile and long long num to allow larger 64-bit numbers, or use string to allow free formatting of the numbers and keep the leading "0".

    Or show details to reproduce the problem.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.