How to test input type before storing C++

Click For Summary

Discussion Overview

The discussion revolves around handling user input in a C++ program, specifically how to validate input before storing it in variables. The context includes practical implementation for a simple calculator program and user prompts for entering numerical values.

Discussion Character

  • Technical explanation
  • Homework-related
  • Debate/contested

Main Points Raised

  • One participant seeks guidance on how to ensure that only valid numerical input is accepted by their C++ program.
  • Another participant provides an example code snippet demonstrating a common technique for input validation using loops and error handling.
  • A participant shares their experience implementing input validation but encounters issues with the program's behavior when invalid input is entered.
  • Concerns are raised about the structure of the code, particularly regarding the use of sequential while loops and potential infinite loops if conditions are not met.
  • Some participants discuss the desired functionality of the program, including prompting the user to enter a number and handling the exit condition appropriately.
  • A later reply presents a revised version of the code that aims to address the issues previously encountered, although it does not clarify whether it resolves all concerns.

Areas of Agreement / Disagreement

Participants express differing opinions on the structure and logic of the code, with some suggesting improvements while others defend their original implementations. The discussion remains unresolved regarding the optimal approach to input validation and program flow.

Contextual Notes

Limitations include potential misunderstandings of program behavior in different contexts (e.g., debug mode vs. normal execution) and the handling of user prompts and input conditions. There is also ambiguity regarding the effectiveness of the proposed solutions in addressing all issues raised.

foges
Messages
52
Reaction score
0
Im sure this is a very basic question. Anyways I need to test the input going to my c++ program before cin stores it. (ive basically written a very simple 4 function calculator program and i just want to make sure that my program does not fail if someone were to enter for example a letter instead of a number). how would i do this?

Thanks
 
Technology news on Phys.org
Basically, you have to try to read, then test to see if the input succeeded, and act accordingly. Here's an example that illustrates a common technique. If the comments aren't enough, ask away! :smile:

Code:
#include <iostream>

using namespace std;

int main ()
{
    cout << "Please enter a number followed by a <return> or <enter>: ";
    double number;
    while ( ! (cin >> number))
    {
        // Enter this loop if input fails because of invalid data.

        cout << "Hey dummy, I said enter a number!  Try again: ";
        cin.clear ();   // reset the "failure" flag

        // The input "cursor" is still positioned at the beginning of
        // the invalid input, so we need to skip past it.

        cin.ignore (1000, '\n');  // Skip to next newline or 1000 chars,
                                  // whichever comes first.  This is why
                                  // you have to follow the input with
                                  // <return> or <enter>.
    }
    cout << "OK, you entered " << number << "." << endl;
    return 0;
}
 
thanks :)
 
Hey, this is my first time writing anything in c++. I happened across this post when I was working so decided I was going to try it. I first applied this to the cin >> minutes and got that to work. I then attempted to apply it to the cin >> end and that is where I encountered the current problems I have been as of yet unable to remedy. If minutes is entered with characters will print "Please enter the amount of minutes." with the cursor beside it instead of moving to a new line and will allow further input which it will put on a new line but if a number is entered afterwards it will not accept it, this works in debug. If end is entered as characters the program loops printing "press 0, Enter to end." if entered as an integer it functions correctly prompting to "press 0, Enter to end." and ends with 0, Enter. In debug the reverse occurs.

Code:
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    cout << "How many minutes did it take to get home today Jeff?\n";
double minutes;
    while ( ! (cin >> minutes)) 
    {                           
        cout << "Please enter the amount of minutes.\n";
        cin.clear();
        cin.ignore(1000, '\n');
    } 
    cout << "It took you " << minutes << " minutes to get home!\n";
    cout << "Press 0, Enter to end\n";
double end;
    while ( ! (cin >> end)) 
    {                       
          cout << "That is not a number.\n";
          cin.clear();
          cin.ignore(1000, '\n');
    }
    do 
    {
     cout << "press 0, Enter to end.\n";
    }while (end != 0); 
    return EXIT_SUCCESS;
}
 
Not sure why you wanted two sequential while loops. And that last while loop will just cause an infinite loop if end != 0 since it gathers no input.

Is this sort of what you're trying to do?

Code:
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    double minutes = 0.0;
    do {
        cout << "How many minutes did it take to get home today Jeff?\n";
        cout << "press 0, Enter to end.\n";
        while ( ! (cin >> minutes))
        {
            cout << "Please enter the amount of minutes.\n";
            cin.clear();
            cin.ignore(1000, '\n');
        }
        if (minutes != 0.0) {
            cout << "It took you " << minutes << " minutes to get home!\n";
        }
    } while (minutes != 0.0);

    return EXIT_SUCCESS;
}
 
I wanted the program to take the value for minute, check if it is an number, prompt to enter a number if not, and then have that value reported. The second part was I did not want the program to simply close I wanted it to be interrupted. I have it prompt "press 0, enter to end" I then wanted it to check if that was a number if not prompt the user to enter a number if the number was not 0 it would simply reiterate to press 0, enter.
 
zabbadahun said:
I wanted the program to take the value for minute, check if it is an number, prompt to enter a number if not, and then have that value reported. The second part was I did not want the program to simply close I wanted it to be interrupted. I have it prompt "press 0, enter to end" I then wanted it to check if that was a number if not prompt the user to enter a number if the number was not 0 it would simply reiterate to press 0, enter.
That's pretty much how the code I posted works, if I understand you correctly. Only difference is that you can exit with 0 right off the start (and are told so) and the same prompt is given for every iteration. Can't see how that could possibly be objectionable behaviour, but I could be wrong.
 
I fixed it this is how it was supposed to work
Code:
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    cout << "How many minutes did it take to get home today Jeff?\n";
double minutes;
    while ( ! (cin >> minutes))
    {                           
        cout << "Please enter the amount of minutes.\n";
        cin.clear();
        cin.ignore(1000, '\n');
    } 
    cout << "It took you " << minutes << " minutes to get home!\n";
double end;
        do 
    {
     cout << "press 0, Enter to end.\n";
     while ( ! (cin >> end)) 
    {                       
          cout << "That is not a number.\n";
          cin.clear();
          cin.ignore(1000, '\n');
    }
    }while (end != 0); 
    return EXIT_SUCCESS;
}
 

Similar threads

  • · Replies 8 ·
Replies
8
Views
5K
  • · Replies 118 ·
4
Replies
118
Views
10K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 14 ·
Replies
14
Views
35K
  • · Replies 39 ·
2
Replies
39
Views
5K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K