cin to accept null value on 'enter'

This is a discussion on cin to accept null value on 'enter' within the C++ Programming forums, part of the General Programming Boards category; im writing a program with a function power() thats asks the user for a number, and the number of times ...

  1. #1
    Registered User xion's Avatar
    Join Date
    Jul 2003
    Posts
    63

    cin to accept null value on 'enter'

    im writing a program with a function power() thats asks the user for a number, and the number of times it needs to be multiplied by itself, with a default of squaring the number if the argument is ommited. but if i dont enter a value the program stalls and doesnt execute. my question is, how to get cin to accept nothing when hitting enter and continue with the rest of the statements?

    heres what i have in main:
    Code:
    int main()
    {
    	double number;
    	int times;
    
    	cout << "Enter in a number:  "; cin >> number;
    	cout << "Enter the times to be multiplied by itself:  "; cin >> times;
    	cout << "Result = " << power(number, times) << endl;
    	return 0;
    }
    once this code hits 'cin >> times' and i just hit enter with no value, the program stalls. thanks in advance.

  2. #2
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    One way is to use getline, and then just parse the string.
    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    
    int main()
    {
        double number = 0.0;
        int times = 2;
    
        cout << "Enter in a number:  ";
        cin >> number;
        cin.ignore(100, '\n'); // Ignore extra characters after the number, including the newline.
                               // This is necessary if you mix >> and getline.
    
        cout << "Enter the times to be multiplied by itself:  ";
        string input;
        getline(cin, input);
    
        if (!input.empty())
        {
            istringstream istr(input);
            istr >> times;
        }
    
        cout << "number = " << number << endl;
        cout << "times = " << times << endl;
        return 0;
    }

  3. #3
    Registered User xion's Avatar
    Join Date
    Jul 2003
    Posts
    63
    thanks. i look into that code. =)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory leaks problem in C -- Help please
    By Amely in forum C Programming
    Replies: 14
    Last Post: 05-21-2008, 11:16 AM
  2. Check if a cin is null
    By HumbuckeR in forum C++ Programming
    Replies: 6
    Last Post: 04-16-2006, 08:16 AM
  3. Tweakable Radar...
    By DoraTehExploda in forum Game Programming
    Replies: 8
    Last Post: 06-07-2005, 10:49 AM
  4. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21