Prime 357

We'll learn something

Site Menu

  • Home
  • Recent Posts
  • Forum
    • Programming Languages
      • C++
    • Website Design & Content Management
      • Wordpress >> Drupal
  • Blogs
  • Books
    • 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

Books

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

Recent comments

  • Thanks
    2 weeks 1 day ago
  • I'm running the conversion
    3 weeks 4 days ago
  • Can't reproduce
    3 weeks 6 days ago
  • Strange one
    3 weeks 6 days ago
  • No customer support
    5 weeks 2 days ago
  • Came to the rescue
    6 weeks 6 days ago
  • Permalink - %postname%
    7 weeks 5 hours ago
  • Downloads are now ready.
    7 weeks 1 day ago
  • Sorry, I'm just having some
    7 weeks 1 day ago
  • Awesome
    8 weeks 2 days ago

New forum topics

  • 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?
  • where do i download?
  • Source connection settings are correct but it appears it's the wrong database
more

Who's online

There are currently 0 users and 0 guests online.

Who's new

  • puzz1ed1
  • bugmenot
  • ClaudiaB
  • beiduo
  • chourmovs

C++

Looking for Contributors

Submitted by Steve on Wed, 18 Jun, 2008 - 14:57
  • C++
  • contributor

I know from the behind-the-scenes statistics that the C++ content is attracting a lot of traffic and return users, more so than the Wordpress to Drupal converter software. Casually glancing at the figures, I'd say half or thereabouts of the C++ traffic is from educational institutions.

The existing content serves a purpose and clearly explains (my opinion) the topic at hand, which is important when learning C++. Unfortunately, I'm unable to keep the content ticking over at a steady pace and therefore I'm looking for contributors.

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

Change of Focus

Submitted by Steve on Tue, 17 Jun, 2008 - 22:50
  • C++
  • PureBasic
  • RealBasic
  • study

Change of focus as regards IT Self Study. I haven't touched C++ since the start of April, this year, but have every intention of finishing the book. No doubt I will have to cover some old ground just to come up to speed again, if anything, that's the frustrating part.

The question is why I haven't continued with the self-study. At the start of April I got involved with creating this site and then shortly after that decided to update my Realbasic application that converts Wordpress Blogs to Drupal. The whole point I was learing C++, leading towards the GUI aspect, is that I could do away with Realbasic and not be held ransom to their pricing structure.

Image - PureBasic

The change comes as of a few hours ago I ordered my copy of PureBasic. This software package is attractively priced and better still, the price covers all future upgrades. Better still, yet again, I have access to the Windows, Linux, Mac and Amiga versions.

This version of basic is implemented slightly differently than Realbasic and Visual Basic so there will be a slight incline of a learning curve to come to grips with the basics. From what I've read thus far it shouldn't be that difficult.

I've also got Ruby waiting in the wings but I've got a feeling it'll be waiting there for a while.

As of tomorrow, I'll go searching for some tutorials, get use to some of the basics and then, maybe within a week, start to the process of converting my Realbasic Wordpress to Drupal converter to Purebasic. That process will be part of the learning experience, so it will take time. That's not to say that I won't stop any Realbasic development. If a bug is found, I'll fix it and release a new version.

  • Steve's blog
  • Login or register to post comments
  • 86 reads

Enhancement # 3 - Trap number followed by non numeric

Submitted by Steve on Wed, 30 Apr, 2008 - 15:58
  • C++
  • cin
  • get()
  • peek()

As you know, the Asterisk Triangle Program has one remaining flaw and it's a flaw that should be addressed.

Presently, if a user enters as input 50prime the number '50' is accepted as valid and the remaining 'prime' is ignored. If a user enters as input 50.5 the number '50' is accepted and the remaining '.5' is ignored. Ideally we need to trap this and force a true integer to be entered.

Replace this line of code

while (!(cin >> rows) or (rows < 1 or rows > 79))

with this

while (!(cin >> rows) or (rows < 1 or rows > 79 or cin.peek() != '\n'))

You'll note that a third condition has been added to the while statement. That being cin.peek() != '\n'. What this is saying is,

"if the next character in the input buffer is not a newline character".

We know that after the execution of cin >> rows that if a true number was entered then all that is left in the input buffer is a newline ('\n') character. The peek() function merely checks for the next character in the input buffer. It doesn't remove the character from the input buffer. An entry such as '50prime' will cause the expression cin.peek() != '/n' to evaluate to true, as it detects the letter 'p', which in turn the body of the while loop is entered.

Here is the complete program code.

// trianglerows-5.cpp
// 30 Apr, 2008.

#include <iostream>

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

Enhancement # 2 - Valid Input Range

Submitted by Steve on Tue, 29 Apr, 2008 - 19:49
  • C++
  • cin

To further enhance the asterisk triangle program the numeric input needs to be restricted to a certain value range. Such a valid range would be 1 through 79. Entering anything greater than 79 and all the visuals go out the window.

Replace the entire while loop with the following while snippet.

   while (!(cin >> rows) or (rows < 1 or rows > 79))
    {
        cout << "Must enter an integer (1 - 79): ";
        cin.clear();              // clear cin error state, if exists
        while (cin.get() != '\n') // clear out non newline characters
            continue;
    }

In reality, only the while statement needed to be replaced as the nothing drastically needed to be changed in the body of the loop. As you can see I did change the cout statement to better inform a user of what is required, a number between 1 - 79.

The while statement could have been written like so:

while (!(cin >> rows) || (rows < 1 || rows > 79))

The || is the same as or and, though not used in this example, && is the same as and.

You will note that the program now detects incorrect data entry, that is any data entry commencing with a non numeric and any numeric entry not falling within the range of 1 through 79.

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

Enhancement # 1 - Trap non numeric input

Submitted by Steve on Tue, 29 Apr, 2008 - 19: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
  • 227 reads

Create a triangle type pattern

Submitted by Steve on Thu, 24 Apr, 2008 - 19:49
  • C++
  • for
  • loop

Write a C++ program that asks the user to enter a number of rows to be printed. It should then display for the first row one asterisk preceded by periods. The second row should display two asterisks preceded by periods and so on until all the rows have been printed as entered by the user.

A sample run would be like so:

Enter number of rows: 5
....*
...**
..***
.****
*****

I've seen many varied questions surrounding this particular problem.

Here's a solution, firstly, just the logic of the code for clarity, not concerning ourselves with error trapping incorrect keyboard input. The object is to understand the reasoning of the logic of addressing the problem at hand.

// nestedloop.cpp
// 29 Nov, 2007.

#include <iostream>
using namespace std;

int main()
{
    int rows, c;
    cout << "Enter the number of rows: ";
    cin >> rows;
    cin.get();
    for (int r = 1; r <= rows; r++)
    {
        for (c = 1; c <= rows - r; c++)
            cout << ".";

        for (; c <= rows; c++)
            cout << "*";
        cout << endl;
    }
    // exit routine
    cout << "\n\n...Press 'ENTER' key to EXIT...\n";
    cin.get();
    return 0;
}

Copy and paste the above into your compiler of choice, compile and run it. As you can see, it works.

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

cin.get (arrayname, size)

Submitted by Steve on Wed, 23 Apr, 2008 - 12: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
  • 187 reads

cin.getline (arrayname, size);

Submitted by Steve on Tue, 22 Apr, 2008 - 23:29
  • C++
  • cin
  • get()
  • getline()

So you want to read an entire line from the keyboard and not be bothered with cin >> getdata; only reading the first word. Then this form of the cin object is for you.

cin.getline(arrayname, size);

This form accepts an entire line entered from the keyboard terminated by the 'ENTER' key. The newline character created by the 'ENTER' key is replaced by a null '\0' character (which is the terminating character required for character arrays). As you can guess from the code snippet, the line of text is ultimately assigned to arrayname variable, a character array, and only receives the number of characters specified by the second parameter, size.

If the number of characters entered is greater than the number specified by the second parameter size the left-over characters remain in the input queue/stream. Remember, the next cin operation will retrieve either some or all of these characters depending upon the type of cin operation that's applied. If the number of characters is less than the parameter size then the input queue is effectively flushed and will not be a problem for the next cin operation.

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

Basic cin operations

Submitted by Steve on Wed, 16 Apr, 2008 - 16:40
  • C++
  • cin

The following attempts to explain the peculiarities of the cin object. Why it does, what it does.

  • Login or register to post comments
  • 221 reads

cin >> getdata;

Submitted by Steve on Wed, 16 Apr, 2008 - 12: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
  • 188 reads
  • 1
  • 2
  • 3
  • 4
  • next ›
  • last »

 Subscribe in a reader

free hit counter


RoopleTheme