C++ string question

Discussion in 'Programmer's Corner' started by stevy123, Mar 12, 2008.

  1. stevy123

    Thread Starter Active Member

    Nov 19, 2007
    61
    0
    Hi all

    I am a beginer programer in c++ and am trying to enter a name say for example joe bloggs but as im only entering in using char i only get joe.

    Below is the class im trying to create. What do i need to modify to get to accept the second part of the name joe bloggs?

    #include <fstream.h>
    #include <string.h>

    class person
    {
    private:
    char name[40];
    int age;
    public:
    void getData(void)
    {
    cout << "\nEnter name: "; cin >> name;
    cout << "\nEnter age: "; cin >> age;
    }
    void showData(void)
    {
    cout << "\n Name: " << name;
    cout << "\n Age: " << age;
    }
    };

    Anyone helps is greatly appricated.
    regards
    Steve
     
  2. Colin Mac

    Member

    Mar 11, 2008
    18
    0
    I'm not much of a C++ programmer but I know cin reads up until whitespace.
    Use getline instead. Also, it looks like you're learning from an old book. C++ has a string class, you needn't use char arrays.
    Code ( (Unknown Language)):
    1.  
    2. #include <iostream>
    3. #include <string>
    4.  
    5. using namespace std;
    6.  
    7. int main()
    8. {
    9.    string name;
    10.  
    11.    cout << "Enter name: ";
    12.    getline(cin, name);
    13.    cout << "Name: " << name <<endl;
    14.    cin.get();
    15. }
    16.  
     
  3. stevy123

    Thread Starter Active Member

    Nov 19, 2007
    61
    0
    Thnaks for your reply

    just one question what is the meaning of this line?

    using namespace std;

    Regards
    Steve
     
  4. Colin Mac

    Member

    Mar 11, 2008
    18
    0
    Namespaces are objects, functions and stuff grouped under a name.

    If you don't put that line there, you have to type std::cout and std::cin etc, instead of just cout and cin.
    That wasn't always the way though. Notice how the .h has been dropped from <iostream.h> to become the now standard <iostream>.
     
  5. cumesoftware

    Senior Member

    Apr 27, 2007
    1,330
    10
    Indeed, cin reads until you press space or enter. You can use getline () from istream (also included if you simply include iostream, since it includes both istream and ostream). In this case, try:
    Code ( (Unknown Language)):
    1. cin.getline (string_name, string_size);
    The function getline () belongs to the iostream class. Don't use it alone, or you will get an error.

    Correct:
    Code ( (Unknown Language)):
    1. string name;
    2. cin.getline (name, 256);
    Wrong:
    Code ( (Unknown Language)):
    1. string name;
    2. getline (name, 256);
    Code ( (Unknown Language)):
    1. string name;
    2. getline (cin, name);
     
  6. Colin Mac

    Member

    Mar 11, 2008
    18
    0
  7. cumesoftware

    Senior Member

    Apr 27, 2007
    1,330
    10
Loading...