Prime 357

We'll learn something

Site Menu

  • Home
  • Recent Posts
  • Forum
    • Programming Languages
      • C++
    • Website Design & Content Management
      • Wordpress >> Drupal
  • Blogs
  • Topics
    • C++
    • Changing hosts - Dummies Guide
    • Wordpress >> Drupal
  • Download Centre
  • Contact us
Home


Image - OpenID

User login

What is OpenID?
  • Log in using OpenID
  • Cancel OpenID login
  • Create new account
  • Request new password

Navigation

  • Recent posts

Topics

  • C++ (The Book)
  • Changing Hosts - a Dummies Guide
  • Wordpress to Drupal

Recent comments

  • Got it solved This page here
    3 hours 55 min ago
  • Links working
    1 day 3 hours ago
  • Thanks... I may be able to
    1 day 9 hours ago
  • 3306 by default
    1 day 19 hours ago
  • Is this the right place to
    1 day 20 hours ago
  • Figured
    3 weeks 6 days ago
  • I'm guessing at this stage
    3 weeks 6 days ago
  • WordPress MU?
    4 weeks 4 hours ago
  • Thanks
    10 weeks 1 day ago
  • I'm running the conversion
    11 weeks 5 days ago

New forum topics

  • What should the port number be
  • WordPress MU?
  • funny little bug in mac version
  • Error: Unable to Insert into Node_revisions table when converting from wordpress 2.6.0 to drupal 6.4
  • index.php?
more

Who's online

There are currently 0 users and 2 guests online.

Who's new

  • oODeathStormOo
  • leruffiant
  • Emtee
  • mnogodet
  • ZioMimmo

failbit

Enhancement # 1 - Trap non numeric input

Submitted by Steve on Tue, 29 Apr, 2008 - 20:42
  • C++
  • cin
  • failbit
  • get()

Okay, lets enhance the asterisk triangle program so that it only accepts numeric input. That is, if a user types in a non numeric then the program should re-request correct input until a number is entered.

Remove these lines:

cin >> rows;
cin.get();

and replace with:

while (!(cin >> rows) ) // checking against cin fail state
{
    cout << "Must enter an integer: ";
    cin.clear();        // reset error state back to false
    cin.get();          // flush out next character
}

An understanding of the cin object is required for this snippet. As the variable rows is defined as an integer type, attempting to assign a non integer to this type will set the cin objects error flag to true. The expression (cin >> rows) returns a boolean value (true or false) relating to the error state of the expression. We can include this error state as a conditional part of a while loop. while loops only continue whilst a condition is true and therefore in this instance we need to check for when not true which means false. Confusing, I know.

Compile and run the program. Enter a single non numeric character. You'll now note that the program asks you to input only an integer. Entering an integer is the only way to exit the loop and continue through to the end.

  • Login or register to post comments
  • Read more
  • 287 reads

cin.get (arrayname, size)

Submitted by Steve on Wed, 23 Apr, 2008 - 13:29
  • C++
  • cin
  • clear()
  • failbit
  • get()

Here is another form of the cin use. This form, cin.get(arrayname, size) is similar to cin.getline(arrayname, size) discussed previously. This form cin.get(arrayname, size) reads an entire line from the keyboard terminated by the 'ENTER' key BUT leaves the newline '\n' character in the input queue. Why it does this I'm not sure and why have such a function which for all intents and purposes is the same as the cin.getline(...) method, I'm not sure either.

Some things to be aware of

If there is an existing newline in the input buffer prior to calling cin.get(arrayname,20);, this form will not accept it, remember it leaves the newline character in the input buffer. The point here is that an error state is created in the cin object; the failbit flag is set to true. No further cin operations are permitted whilst the error flag is set to true. In order to remove the error flag this command cin.clear(); is required. It resets the cin error state back to false.

The above is not applicable if the input buffer contains normal characters ending with a newline character prior to calling the cin.get(arrayname, 20);. What occurs in this instance is that the errant characters or characters already in the input buffer as a result of a previous cin operation are assigned or allocated to the character array arrayname. The newline character is left in the input buffer.

Another situation arises whereby the user types in more characters than is specified by the size parameter of the cin function. No error state is recorded and the character array arrayname only receives the number of specified characters. The remaining characters are left in the input buffer.

The following code snippet should explain the various workings of this topic. The code, as is, will create an error state, simply uncomment the line after cin.get(line, 20);.

// File : testcin3.cpp
// Author : Steven Taylor
// Date : 23 Apr 2008
#include <iostream>
using namespace std;
int main()
{
    char getdata;
    cout << "Enter one character: ";
    cin >> getdata;
    cin.get();   // clear out very next character (newline)
   
    char line[20];
    cout << "\nEnter a line of text 20 characters max: ";
    cin.get(line,20);
    cout << "\nLine of text entered : " << line;
    //cin.get();      // flush out the newline character
   
    char line2[20];
    cout << "\nEnter another line of text 20 characters max: ";
    cin.get(line2,20);
    cout << "\nSecond line of text entered : " << line2;
   
    cout << "\n\nNow at the end of the program" << endl;
    cout << "First character of line[20]  : " << line[0] << " character code is : " << (int)line[0] << endl;
    cout << "First character of line2[20] : " << line2[0] << " character code is : " << (int)line2[0]<< endl;
   
    if (cin.eof())
        cout << "\n cin.eof() == true";
    else
        cout << "\n cin.eof() == false";
    if (cin.fail())
        cout << "\n cin.fail() == true";
    else
        cout << "\n cin.fail() == false";
   
    // exit routine
    cin.clear(); // only use this if there is potential for an error state.
    while (cin.get() != '\n')
        continue;
    cin.get();
    return 0;
}

As an aside, if there is no error state, issuing the command cin.clear(); has no side effects, that is, errors are not reported simply because no error exists to start with. It's harmless.

Play with the program. You will note that if you input more than a single character for the first input, that it adversely affects the following cin methods. I'll deal with flushing the input stream/buffer/queue in a separate article but in the interim the exit routine should be a clue as to how to flush the input buffer.

  • Login or register to post comments
  • 235 reads

cin >> getdata;

Submitted by Steve on Wed, 16 Apr, 2008 - 13:35
  • C++
  • cin
  • eofbit
  • failbit
  • input stream
cin >> getdata;

This is the basic form of retrieving characters from the keyboard. The characters typed at the keyboard are sent to the input stream terminated by the 'ENTER' key. Once in the input stream they are allocated or assigned to the receiving variable, from the above example, getdata. What this means is that prior to the 'ENTER' key being pressed there is no control or checking of the characters typed.

So far, so good but there is a catch, well quite a few actually and we'll ease into them.

Firstly, this form only reads alphanumeric characters up until the first white space, tab, null or newline ('ENTER' key) character. (I'm not too sure how to type in a 'null' character, maybe leave that one for later)

Lets assume a user typed, this is really awkward stuff [ENTER]

From our example at the top of the page cin >> getdata; only the word this would be assigned (or attempted to be assigned/allocated) to getdata. This is because cin only accepted characters up until the first whitespace or only retrieves a series of characters (words) not containing spaces. The remaining words is really awkward stuff [ENTER] are left in the input stream. This is the source of many problems as the very next cin >> getwhatever; will retrieve the next word from the input stream, in our case, is. Still, the input stream now contains really awkward stuff [ENTER]

In general, if a line of text, which includes spaces and/or tabs, needs to be input, do not use this form of the cin object. Yes, there are other ways and there are ways to deal with this problem if using this form of the cin object and they will be the subject of another entry.

Returning to our example at hand cin >> getdata; there are other factors that come into play. The main 'other factor' is the data type of the variable getdata. To this point that hasn't been considered but as you'll soon see it plays an important and significant part of this whole cin >> getdata; saga.

Here is a more complete snippet of code in how a basic 'get data from the keyboard' is implemented.

char getdata[20];
cout << "Please enter your name? ";
cin >> getdata;

The above code snippet, if applied to our example above, would not throw any errors as the variable getdata is actually a char array having the ability to store 20 characters (enough for our purposes). Those characters being alphanumeric, which means numbers or letters or both. We still have the same issue that only the first word is received and assigned to the variable getdata.

Now the fun starts. Let's change the data type of the variable getdata from being an array to just a plain old char variable. Our snippet of code becomes:

char getdata;
cout << "Please enter your name? ";
cin >> getdata;

A line of text, including spaces and/or tabs, can still be entered, ending up in the input stream. The result is that only the first character of the input stream will be assigned to the variable getdata. The input stream still contains the user entered text, minus the first character. This behaviour occurred as the data type of the receiving variable getdata is of type char. This means it can only hold or store a single character (digit or letter).

Whether we need to receive only a single character or a word, if the input stream still contains characters then the next cin >> getwhatever; operation will retrieve them. This might not be the expected or intended result.

Now the real fun starts. What if the data type of the receiving variable is of type integer. It's only expecting numbers not letters. Here's our snippet of code:

int getdata;
cout << "Please enter your age? ";
cin >> getdata;

If a user types in abc where is that to be stored? The variable getdata can't receive it as it can only hold an integer (a number). What occurs is that the cin object throws an error and sets it's failbit to 'true'. The other error bit of the cin object is the eofbit which is an 'End of File' (EOF) error. In the context of this discussion the eofbit is not relevant.

The consequences of the cin object throwing an error (failbit or eofbit) is that no further calls to the cin object has any effect, they are ignored. This means if your program does in fact make use of the cin object after an error, it simply won't work as intended.

To clear the error state of the cin object issue this command:

cin.clear();

This clears the error state and further processing of cin object is allowed.

As you've probably guessed there may still be characters remaining in the input stream which need to be dealt with as well. On this point, the newline (\n) character 'ENTER' remains in the input queue/stream even upon successful keyboard data input. For this discussion that's not overly relevant as the very next cin object disregards any newline character if it's the first in the input queue/stream. This aspect becomes relevant when other forms of the cin object follow the basic form of cin >> getdata;. This will be the subject of another article.

How do we trap for incorrect data input? How do we know when to clear the cin object's error state? How do we know....? Well these are all valid questions and will be answered in the next article.

Related article : Asterisk Triangle Program in which trapping incorrect data input and restricting input to a valid numeric range is discussed.

  • Login or register to post comments
  • 238 reads

 Subscribe in a reader

free hit counter


RoopleTheme