Thread: how to read in a negative number using cin

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    221

    how to read in a negative number using cin

    is there any possible way to read in a negative number if they put in, lets say a -3, but the same function shoudl still be able to read a positive value?

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Of course. Every type can store negative and positive numbers. Here is an example:

    int num =0;
    cout<<"Enter a positive or negative integer:\n";
    cin>>num;
    cout<<num<<endl;

  3. #3
    Cheesy Poofs! PJYelton's Avatar
    Join Date
    Sep 2002
    Location
    Boulder
    Posts
    1,728
    Unless you declare the variable as unsigned, then you shouldn't have any problem with entering in a negative value.

  4. #4
    Registered User
    Join Date
    Dec 2002
    Posts
    221
    what if im using multiple input at once
    i want to be able to put in something like

    -5 3/4

    and cin it as

    char trash;
    int wholenumber,num,denom;
    cin >> wholenumber >> trash >> num >> trash >> denom;


    would that work?

  5. #5
    Registered User
    Join Date
    Dec 2002
    Posts
    221
    ah it does work
    thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. read specific number of chars from stream
    By ch4 in forum C++ Programming
    Replies: 2
    Last Post: 03-02-2008, 12:49 PM
  2. scanf oddities
    By robwhit in forum C Programming
    Replies: 5
    Last Post: 09-22-2007, 01:03 AM
  3. I am lost on how to read from file and output to file?
    By vicvic2477 in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2005, 11:52 AM
  4. how to handle integer overflow in C
    By kate1234 in forum C Programming
    Replies: 8
    Last Post: 04-23-2003, 12:20 PM
  5. Help! Can't read decimal number
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 09-07-2001, 02:09 AM