-
the newbie returneth
#include<iostream.h>
#include<conio.h>
const int MAX=4;
class person
{
char name[10];
public:
void display()
{
cout<<name;
}
void accept()
{
cout<<"ENter Name";
cin>>name;
}
};
void main()
{
person *parr[MAX];
for(int i=0;i<MAX;i++)
{
parr[i]=new person;
parr[i]->accept();
}
for(int j=0;j<MAX;j++)
{
parr[i]->display();
}
getch();
}
1)..#include<Iostream> does not work..it doesnt recognise cin/cout/<</>> etc...I have 2 add the ".h" at the end.
2) getch()..the function I think is supposed 2 b used to halt the program so tt the user can read the screen output before the Window vanishes...it apparently stops the program right before any output is done on screen...
3)..the program here is giving me garbage output..cant figure out y.Probably the error would be painfully obvious the next time I look at the code..but still...
-
1. You need to have a using namespace std; in there.
2. Before the getch, use cout << flush;
Code:
#include<iostream>
#include <string>
#include<conio.h>
using namespace std;
const int MAX = 4;
class person {
string name; // Changed this so you're not limited on names
public:
void display() {
cout << name << endl;
}
void accept() {
cout << "Enter Name: ";
cin >> name;
}
};
int main() {
person parr[MAX]; // You don't need a pointer since it's fixed
for(int i = 0; i < MAX; ++i) {
parr[i]->accept();
}
for(int j = 0; j < MAX; ++j) {
parr[j]->display(); // Changed this to j from i
}
cout << flush; // endl actually does this anyway, but its good practice
getch();
return 0;
}
Hopefully the string change should fix 3.
-
<< and >> aren't overloaded for string. Use getline to input it and cout << name.c_str() for output.
-
They are, they act in exactly the same way you'd expect (get up to the first whitespace character).
getline gets up until a newline.
-
Strange, I usually get an error when doing
string str("Hello!");
cout << str << endl;
-
You have to be using the templated iostreams (#include <iostream>) or it won't work.
-
I do. But I haven't tried in a while. I'll do it now.
Ok, it works. Never mind.