1

Please have a look at the following code

#include <iostream>
#include <iomanip>

using namespace std;

double hypontenuse(double,double);


int main()
{
    double side1 = 0;
    double side2 = 0;

    cout << "Enter side1 (-1 to exit)" << endl;
    cin >> side1;

    while(true)
    {

        if(side1==-1)
        {
            break;
        }

        cout << "Enter side2" << endl;
        cin >> side2;

        double result = hypontenuse(side1,side2);

        cout << "The Hypontenuse of the Right Triangle is: " << setprecision(2) << fixed << result << endl;


        cout << "Enter side1 (-1 to exit)" << endl;
        cin >> side1;
    }
} 

double hypontenuse(double side1, double side2)
{
    double result = (side1*side1)+(side2*side2);

    return result;
}

I am new to C++. In this code, if I gave an input which is not valid (space, tab, letter, etc) this code suddenly become an infinite loop. I need to ignore such invalid inputs, display a message, and come back to the starting position. How can I do that? Please help!

PeakGen
  • 21,894
  • 86
  • 261
  • 463

2 Answers2

1

You always need to check if your input was successful. Typically, this is done by just converting the stream to a Boolean value:

if (std::cin >> value) {
    process(value);
else {
    // recover from the error
}

Recovering from a wrong input consists of, at least, two parts:

  1. Setting the stream back into a state where it does anything, e.g., using std::cin.clear().
  2. Getting rid of any offending input. How this is done exactly depends on your needs. For example, you might be able to just ignore individual characters or everything up to the end of the line.

The code for ignoring characters looks something like one of these:

std::cin.ignore(); // ignores one character
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore until end of line
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • 1
    I have given the necessary code snippets in my answer already! You need to determine what you need to do. If you have specific questions I'm happy to answer but a general "please fix my code" won't fly. – Dietmar Kühl Oct 07 '12 at 19:12
0

Personally, my suggestion would be to use good old C "fgets()" and "sscanf()".

However, look at this link:

It does the following:

1) uses std::getline(std::cin, str) to read your raw input (analogous to "fgets)")

2) uses std::ws to eat extaneous whitespace (like tabs, characters and newlines)

Unfortunately, it doesn't help validate the input (which sscanf() would do for you in one statement).

'Hope that helps

==============================================================

Q: can you please edit my code? It is bit hard to understand :( – Sepala

A: Fair enough. Here goes:

#include <stdio.h>

double 
hypontenuse(double side1, double side2)
{
    return (side1*side1)+(side2*side2);
}


int 
main(int argc, char *argv[])
{
    double side1 = 0;
    double side2 = 0;
    char buff[80];

    while(true)
    {
      printf ("Enter side1 and side2 (-1 to exit): ");
      fgets (buff, sizeof (buff), stdin);
      int iret = sscanf (buff, "%lf %lf", &side1, &side2);
      if (side1 == -1)
        break;
      if (iret != 2)
        continue;

      double result = hypontenuse(side1,side2);
      printf ("The Hypontenuse of the Right Triangle is: %.02lf\n", result);
    }
    printf ("Done.\n");
    return 0;
} 
Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • This advice is at best incomplete: Even `getline` mustn't be used outside a boolean context. The input stream could already be exhausted or closed, and the extraction would fail. – Kerrek SB Oct 07 '12 at 17:55