Results 1 to 3 of 3

Thread: cin.get() problem

  1. #1
    League / Affiliates Representant <Shifty's Avatar
    Join Date
    May 2010
    Location
    The Netherlands, Roermond
    Posts
    100

    Post cin.get() problem

    This schoolyear I'll be learning C++ at school, and yesterday i received my books wich i'll be using and because i was a bit curious i already started to read in it and eventually i was asked to make a simple program that will caculate your annual salary.

    Code:
    #include <iostream>
    #include <conio.h>
    using namespace std;
    
    int main()
    {
    	const int MONTH_YEAR = 12;         // 12 month in a year
    	int salary;                                        // monthly salary
    	cout << "Typ in your salary" << endl;
    	salary = cin.get();
    
    	int annualSalary = salary * MONTH_YEAR;
    	cout << "Your annual salary is " << annualSalary << " euro" << endl;
    	system("PAUSE");
    	return 0;
    }
    I think the code is pretty clear: You'll be asked to give a salary lets say 4000, then it give you your annual salary by multiplying your salary with 12 (MONTH_YEAR) but 4000 * 12 = 48000 and not 624 like i get

    i'm assuming it has something to do with cin.get() though in the book they were not really clear about what it did (remembering the value i gave salary i think)
    As finishing touch god created the Dutch

  2. #2
    Administrator James's Avatar
    Join Date
    May 2010
    Location
    on the intraweb
    Posts
    3,180

    Default

    This works.
    Use cin not cin.get. I've always used cin.get with characters not integer data types, or when you're reading from a file you would use cin.getline().

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        const int month_year = 12;
        int salary;
        int annualSalary;
    
        cout << "Type in your salary" << endl;
        cin >> salary;
    
        annualSalary = (salary * month_year);
        cout << "Your annual salary is " << annualSalary << " euros" << endl;
        system("PAUSE");
        return 0;
    }

  3. #3
    League / Affiliates Representant <Shifty's Avatar
    Join Date
    May 2010
    Location
    The Netherlands, Roermond
    Posts
    100

    Default

    Ok thanks james it worked.

    Use cin not cin.get. I've always used cin.get with characters not integer data types, or when you're reading from a file you would use cin.getline().
    I was already wondering if that was the problem. They could have mentioned this in the book though. :P
    As finishing touch god created the Dutch

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •