Classes

who can tell me why this program work incorrectly?

#include<iostream>
using namespace std;

class dat
{
int n;
char *names[20];
public:
dat();
friend void set(dat ob);
void show();
};



dat::dat()
{

n=0;
}

void set(dat ob)
{
cout<<"n=";
cin>>ob.n;
for(int i=0;i<ob.n;i++)
{
ob.names[i]=new char[30];
gets(ob.names[i]);
}
}

void dat::show()
{
cout<<"\n\nDATA\n";
for(int i=0;i<n;i++)
cout<<names[i]<<endl;
}

int main()
{

dat ob;

set(ob);

ob.show();

return 0;
}
my compiler wrote:
In function 'void set(dat)':
29:17: error: 'gets' was not declared in this scope


You didn't #include <cstdio> .
Of course, since this is C++ code, you really should be using std::string instead.
Never mix C and C++. Use all of one, or all of the other.
I've written with getline but it also don't work. when I give n=3 it takes only 2 words and the thirth one is empty string but can't understand why

#include<iostream>
using namespace std;

class dat
{
int n;
char *names[20];
public:
dat();

friend void set(dat ob);
void show();
};



dat::dat()
{

n=0;
}

void set(dat ob)
{
cout<<"n=";
cin>>ob.n;
for(int i=0;i<ob.n;i++)
{
ob.names[i]=new char[30];
cin.getline(ob.names[i],30);
}
}

void dat::show()
{
cout<<"\n\nDATA\n";
for(int i=0;i<n;i++)
cout<<names[i]<<endl;
}

int main()
{

dat ob2;

set(ob2);

ob2.show();

return 0;
}
Last edited on
friend void set(dat ob);
ob is passed by value. Nothing is done to the original. The fact that it affects the original at all is because you got lucky by using pointers...but what do the pointers point to??
Last edited on
#include<iostream>
using namespace std;

class dat
{
int n;
char *names[20];
public:
dat();

friend void set(dat &ob);
void show();
};



dat::dat()
{

n=0;
}

void set(dat &ob)
{
cout<<"n=";
cin>>ob.n;
for(int i=0;i<ob.n;i++)
{
ob.names[i]=new char[30];
cin.getline(ob.names[i],30);
}
}

void dat::show()
{
cout<<"\n\nDATA\n";
for(int i=0;i<n;i++)
cout<<names[i]<<endl;
}

int main()
{

dat ob2;

set(ob2);

ob2.show();

return 0;
}

the result is the same
You left a newline in the input buffer after doing cin>>ob.n;, so a blank string got read into ob.names[0] when you called cin.getline(ob.names[i],30);.

In other words, put something like
cin.ignore(80, '\n');
right after cin>>ob.n;.
Thanks a lot
I find this a good time to talk about this.

What if the user needs to enter more than 20 names?

@long double main: what if the user types more than 79 characters after the number?
@L B:
Eh, okay...

cin.ignore(numeric_limits<streamsize>::max(), '\n');
(of course, you need #include <limits> )

But really, this program should be using std::string and vectors to store all the names. (I think I mentioned using std::string before, briefly)
char *names[20]; why make an arrow of pointer chars? use a vector of strings.
std::vector<std::string> names;
Topic archived. No new replies allowed.