C++ string question

Thread Starter

stevy123

Joined Nov 19, 2007
61
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
 

Colin Mac

Joined Mar 11, 2008
18
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.
Rich (BB code):
#include <iostream>
#include <string>

using namespace std;

int main()
{
   string name;

   cout << "Enter name: "; 
   getline(cin, name);
   cout << "Name: " << name <<endl;
   cin.get();
}
 

Colin Mac

Joined Mar 11, 2008
18
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>.
 

bloguetronica

Joined Apr 27, 2007
1,541
I'm not much of a C++ programmer but I know cin reads up until whitespace.
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:
Rich (BB code):
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:
Rich (BB code):
string name;
cin.getline (name, 256);
Wrong:
Rich (BB code):
string name;
getline (name, 256);
Rich (BB code):
string name;
getline (cin, name);
 

bloguetronica

Joined Apr 27, 2007
1,541
Top