View Single Post
  #1 (permalink)  
Old October 29th, 2004, 09:52 AM
gillianbc gillianbc is offline
Authorized User
 
Join Date: Nov 2003
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default Char array cin query (additional)

Thanks for all you replies to my recent "Basic char array and cin query". I was really wanting to understand what was going on rather than alternative solutions hence this new thread. I'm working my way through "Beginning C++" so I don't want to introduce things that I haven't yet covered in the chapters. This query arose from the solutions to one of the exercises. In the code below (extracted directly from solutions to exercises in the book), the function header for GetData has one param that is passed by reference and one that isn't yet it still seems to work and I can't understand why.
The array gets populated by cin and its value gets passed back to main() even though it's not passed by reference - why ? What's so special about cin ? What's so special about char arrays that you don't need to use
Code:
void GetData(int& number, char& name[])
It's only cin that seems to do this. I tested this out by adding a simple assignment statement in after the cin line (hence the commented out line: name = "John") and in a debugger, you can see that name gets set to John until the end of the function but then reverts to the value input using cin.
Code:
#include <iostream.h>
void GetData(int& number, char name[])
{
    cout << "Enter a number: \n";
    cin >> number;

    if (number != 0)
    {
        cout << "And a name: \n";
        cin >> name;
        //name = "John";
    }    
}
void PutData(int number,char name[])
{
    cout    << "Thank you.  Your number and name were " << number
            << " and " << name << "\n";
}
void main()
{
    int number;
    char name[15];
    for (;;)
    {
        GetData(number, name);
        if (number==0)
            break;
        PutData(number,name);
    }    
}
Gill BC
__________________
Gill BC
Reply With Quote