GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 02-Jul-2009, 13:57
nowocien nowocien is offline
Awaiting Email Confirmation
 
Join Date: Nov 2008
Posts: 30
nowocien is an unknown quantity at this point

Couple of questions


how does the cin.get() != '\n' know too look for one character and then check for a new line at the end.. i have also seen this used the same way with numeric data in which case this same expression checks to see if you entered nothing but numbers with not other characters at the end.. accept for the new line??

CPP / C++ / C Code:
cout << " Do you wish to continue (y or n) ? ";
cin >> y_or_n;
y_or_n = tolower(y_or_n);
if (cin.get() != '\n') {
cin.ignore(2000, '\n');
cerr << "Trailing characters.  Try again." << endl;}



also the strcmp function. here is a definition i found for the return value: Returns an integral value indicating the relationship between the strings:
A zero value indicates that both strings are equal.
A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.

i wrote a piece of code to see how this could be use to sort alphabetically and it seems that in the definition the GREATER character value refers to a LOWER asscii character value?? from experimintation i get whats happeing but this definition seems off.. does that mean that when referring to the value of a character in C++ the lower values are really greater values?? here is the part of the code i wrote to test this. just snippets.

sort is called from main.
CPP / C++ / C Code:
//bubble sort
void sort(Employee* employee, int n) {

     int i, j;
     Employee temp;

     for (i = n - 1; i > 0; i--) {
	 for (j = 0; j < i; j++) {
	     if (employee[j] > employee[j+1]) { //overloaded >
		 temp          = employee[j];
		 employee[j]   = employee[j+1];
		 employee[j+1] = temp;
	     }
	 }
     }
 }

//non-friend helper
int operator>(const Employee& a, const Employee& b){
  int rc = 0;
  if (strcmp(a.Name(), b.Name()) > 0)
     rc = 1;

  return rc;
}

i hope I am clear enough.. thanks
nowocien
  #2  
Old 03-Jul-2009, 10:00
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Couple of questions


Quote:
Originally Posted by nowocien
how does the cin.get() != '\n' know too look for one character and then check for a new line at the end

cin.get() doesn't know anything. It just retrieves the next character from the input stream.

When the user presses keys on the keyboard, the characters are placed in the input stream. With a "normal" program that doesn't do anything in particular with the "usual" setup, nothing is actually available to programs until the user presses the 'Enter' key.

So...

If you press the 'y' key and the 'Enter' key, there are two characters in the input stream presented to user's program: the 'y' character and the '\n' (newline) character.

The first call to cin.get() retrieves the 'y' character and removes it from the input stream. The second call to cin.get() retrieves the '\n' and removes it from the input stream. The input stream is now empty.

If you try something like cin.ignore(), the program will wait until there is something else in the input stream (so that it can ignore it). In other words the user will have to press the 'Enter' key some time (sooner or later) in order for the program to continue.

If you press 'y' and then 'e' and then 's' and then 'Enter' there will be four characters in the input stream. The first call to cin.get() retrieves the 'y' character and removes it from the input stream. The second retrieves the 'e' and removes it from the input stream.

Now, the call to cin.ignore(2000) will remove (and throw away) as many as 2000 characters from the input stream, up to and including a '\n' character. In other words, it will stop scanning when it has scanned 2000 chars or until it sees a '\n', whichever occurs first. Notice that if there were more than 2000 characters in the input stream and if there were no '\n' among the first 2000 characters, the input stream will not be empty.


Quote:
Originally Posted by nowocien
,,,with numeric data


Assuming that the input stream is initially empty, if the user enters a number, such as "123", there will be four characters in the input stream: '1' and '2' and '3' and '\n'. If the program uses "cin>>" to read an integer, the program scans the input stream and retrieves and removes characters that can be part of an integer ('0' through '9') When the scanner encounters something that can not be part of an int, it stops scanning at that point, and that character is not removed from the input stream. The digits that were scanned are converted to the integer value, and the '\n' is still in the input stream.

Then cin.get() retrieves and removes the '\n' character and the input stream is now empty again.

If the user enters something like "1.2", there are four characters in the input stream: '1' and '.' and '2' and '\n'. Now if the program uses "cin>>" to read an integer, the program scans the input stream and retrieves and removes '1'.

The next character in the stream is '.' which can not be part of an integer, so the program stops scanning. The value of the integer is 1, and the '.' is not removed from the input stream. So the '.' character will be the next one to be scanned.

At this point, the cin.get() sees the '.' and removes it. The program knows that the user entered something after the integer part.

Example:
CPP / C++ / C Code:
#include <iostream>

using namespace std;

int main()
{
    int x = -10000000;

    cout << "Enter an integer: ";
    cin >> x;
    if (!cin) {
        cout << "Could not scan an int from your input." << endl;
        return 0;
    }
    cout << "x = " << x << endl;
    if (cin.get() != '\n') {
        cout << "There was some extra stuff." << endl;
        cin.ignore(2000, '\n');
    }
    return 0;
}


A couple of runs:
Code:
Enter an integer: 123 x = 123

Code:
Enter an integer: 1.23 x = 1 There was some extra stuff.

Code:
Enter an integer: .123 Could not scan an int from your input. x = -10000000 There was some extra stuff.
Quote:
Originally Posted by nowocien
...in the definition the GREATER character value refers to a LOWER asscii character value??
OK, let's talk about sorting arrays of chars:

The strcmp() function works as advertised, by comparing numeric values of the characters, so let's investigate that.

Think about it: if you want to alphabetize things, you sort in increasing order, right? That is, you want 'a' to be less than 'b', right? It "turns out" that ASCII conveniently orders them like that. See Footnote.

I'll go one step further:

Now, what if one of the words starts with 'A' and another starts with 'a'. Which one would appear first in the sorted list? In my dictionary, the Upper Case appears before the lower case. It "turns out" that in ASCII, all Upper Case chars appear before any lower case characters. Again, that's convenient for sorting according to numeric values.
CPP / C++ / C Code:
#include <iostream>

using namespace std;

int main()
{

    char first, second;


    cout << "Enter two characters: ";
    while (cin >> first >> second) {
        if ((first == '\n') || (second == '\n')){
            break;
        }
        cout << "First  = " << first << " = " << (int)first << " decimal"
             << endl
             << "Second = " << second << " = " << (int)second << " decimal"
             << endl << endl;
    }
    return 0;
}

A run:
Code:
Enter two characters: A B First = A = 65 decimal Second = B = 66 decimal Enter two characters: a b First = a = 97 decimal Second = b = 98 decimal Enter two characters: A Z First = A = 65 decimal Second = Z = 90 decimal Enter two characters: a z First = a = 97 decimal Second = z = 122 decimal Enter two characters: Z a First = Z = 90 decimal Second = a = 97 decimal

Bottom line: if your sort function doesn't work as expected, it is because of a bug in your program, not a bug or mis-statement in the definition of strcmp().


Regards

Dave

Footnote: Some might point out that it is not absolutely required that characters in C or C++ use ASCII encoding. I use it as an example because that's probably what your system uses. Regardless of that, it is required that strcmp work as advertised.

Furthermore, I will say that I can't think of a very good reason to use char arrays in a program like this anyhow (except, maybe to show how to use C legacy functions like strcmp()).

In my opinion C++ strings are much more powerful (easier to use) and less prone to problems, and almost certainly would be considered more appropriate by "most" C++ programmers (and their managers).

On the other hand, we have no insight into your actual program specification or the requirements of your assignment, so...
Last edited by davekw7x : 03-Jul-2009 at 10:56.
  #3  
Old 03-Jul-2009, 11:49
nowocien nowocien is offline
Awaiting Email Confirmation
 
Join Date: Nov 2008
Posts: 30
nowocien is an unknown quantity at this point
Talking

Re: Couple of questions


thanks DAve, you really are outstandng!!


Daniel
  #4  
Old 03-Jul-2009, 11:52
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Couple of questions


In the example of my previous post:
CPP / C++ / C Code:
#include <iostream>

using namespace std;

int main()
{
    int x = -10000000;

    cout << "Enter an integer: ";
    cin >> x;
    if (!cin) {
        cout << "Could not scan an int from your input." << endl;
        //return 0;
    }
    cout << "x = " << x << endl;
    if (cin.get() != '\n') {
        cout << "There was some extra stuff." << endl;
        cin.ignore(2000, '\n');
    }
    return 0;
}



The output from that program would be:

Code:
Enter an integer: 123 x = 123

Code:
Enter an integer: 1.23 x = 1 There was some extra stuff.

Code:
Enter an integer: .123 Could not scan an int from your input.

When I comment out the return line in the test:
CPP / C++ / C Code:
    if (!cin) {
        cout << "Could not scan an int from your input." << endl;
        //return 0;
    }

Now I get the output is as shown in my previous post:
Code:
Enter an integer: 123 x = 123

Code:
Enter an integer: 1.23 x = 1 There was some extra stuff.

Code:
Enter an integer: .123 Could not scan an int from your input. x = -10000000 There was some extra stuff.

The point being that, if the scan failed, the value of x is unchanged. Bottom line: when reading numeric quantities, you should always test the state of cin (or whatever other input stream that you are using) to make sure that the scan was successful. If the scan was not successful, don't try to use the value of whatever you were trying to read.

I regret the error. I try really hard to post actual runs from my program examples, but I blew it this time.

Regards,

Dave
  #5  
Old 03-Jul-2009, 12:01
nowocien nowocien is offline
Awaiting Email Confirmation
 
Join Date: Nov 2008
Posts: 30
nowocien is an unknown quantity at this point

Re: Couple of questions


you didnt blow anything.. your the best.. thanks Again


Daniel
 
 

Recent GIDBlogToyota - 2009 May Promotion by Nihal

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Couple of Socket Questions nugol C++ Forum 2 26-Aug-2006 13:38
Just a couple questions. Philsco MySQL / PHP Forum 3 23-Aug-2006 23:04
A couple questions about Fl_Tabs WW. FLTK Forum 3 07-Oct-2004 08:04
Couple of questions Memory and CD RW schuumi Computer Hardware Forum 3 15-Sep-2004 16:32
Multi-Lingual Webpages & A Couple General Questions. dwaunthomas Web Design Forum 5 15-May-2004 12:07

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 16:12.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.