Thread: cin to int

  1. #1
    Registered User
    Join Date
    Jun 2017
    Posts
    88

    cin to int

    Hello. I'm going back over some C++ stuff. The following program is the usual way I might get user input into a private member of a class.
    Code:
    #include <iostream>
    
    class Account {
    private:
        int a{ 0 };
    
    public:
        Account() {}
        void setA(int a) {
            Account::a = a;
        }
        int getA() {
            return a;
        }
    };
    
    int main() {
    
        Account p;
        
        std::cout << "Enter int: ";
        int copy;
        std::cin >> copy;
        p.setA(copy);
    }
    I would like to avoid creating the copy variable though. It seems to me like it is a wasted step when I should be able to just put cin strait into the set function. I know the reason why I can't is that the data from cin is a stream which needs to be converted into an int. Is it possible to do this without creating a variable to do only this?

    Code:
    int main() {
    
        Account p;
        
        std::cout << "Enter int: ";
        p.setA(std::cin.toInt);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You could write a readA member function to read from an input stream into the member variable:
    Code:
    #include <iostream>
    
    class Account {
    private:
        int a{ 0 };
    
    public:
        Account() {}
    
        void setA(int a) {
            Account::a = a;
        }
    
        int getA() {
            return a;
        }
    
        void readA(std::istream& in) {
            in >> a;
        }
    };
    
    int main() {
    
        Account p;
    
        std::cout << "Enter int: ";
        p.readA(std::cin);
    }
    By the way, getA should be declared const. You arguably don't need readA to be a member function or a friend since you can implement it using setA, but then implementing it using setA would basically be moving what you did in main with the temporary variable to readA, which is not what you desire.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Tags for this Thread