Apr 12, 2012 at 9:27pm UTC
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;
}
Apr 12, 2012 at 9:36pm UTC
Never mix C and C++. Use all of one, or all of the other.
Apr 12, 2012 at 9:41pm UTC
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 Apr 12, 2012 at 9:43pm UTC
Apr 12, 2012 at 9:42pm UTC
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 Apr 12, 2012 at 9:43pm UTC
Apr 12, 2012 at 9:45pm UTC
#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
Apr 12, 2012 at 9:51pm UTC
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;
.
Apr 12, 2012 at 9:56pm UTC
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?
Apr 12, 2012 at 10:00pm UTC
@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)
Apr 13, 2012 at 2:06am UTC
char *names[20]; why make an arrow of pointer chars? use a vector of strings.
std::vector<std::string> names;