#include<iostream.h>
#include<conio.h>
class A
{
int a[10];
char name[10];
public:
void read();
void display();
};
void A::read()
{
cout<<"enter rno name";
for(int i=0;i<3;i++)
{
cin>>a[i];
cin>>name;
//cin>>a[i];
}
}
void A::display()
{
//cout<<count;
for(int i=0;i<3;i++)
cout<<a[i]<<name;
}
//int A::count;
main()
{
clrscr();
A x;
x.read();
x.display();
getch();
}

here i need to read 3 rollnumbers and 3 names
and print the same.
but am getting only the last name for all rollnumbers
how could i code to get individual name for every rno.

Recommended Answers

All 3 Replies

1) use code tags!
2) include<iostream> instead of <iostream.h>
3) don't use conio.h (replace getch() with cin.get(); )
4) prefix cin and cout with std::

Your class only allows one name, you need to define an array of 3 names and then use it as an array in the methods:

class A
{
    int a[3];
    char name[3][20];
public:
    void read();
    void display();
};
void A::read()
{
    cout<<"enter rno name";
    for(int i=0;i<3;i++)
    {
        cin>>a[i];
        cin>>name[i];
    }
}
void A::display()
{
    for(int i=0;i<3;i++)
        cout<<a[i]<<name[i];
}
#include<iostream.h>

<iostream.h> is an old header that new compilers might not recognize. This is a real problem. My compiler barfs on your code because <iostream.h> is not supported anymore. If you use an old compiler that does not support the new headers, you are selling yourself short and cannot learn the best parts of C++. If you use a compiler that supports both old and new headers, start using the new ones because the old ones are being phased out at warp speed. ;)

char name[10];

This is where the new C++ library can help you. Instead of using arrays of char for strings, you can use the C++ string class and working with strings gets a whole lot easier when you start to get into dynamic sizing and common string operations:

#include <iostream>
#include <string>

class A
{
    int a[3];
    std::string name[3];
public:
    void read();
    void display();
};

void A::read()
{
    for (int i = 0; i < 3; i++)
    {
        std::cout << "enter rno name: ";
        std::cin >> a[i] >> name[i];
    }
}

void A::display()
{
    for (int i = 0; i < 3; i++)
    {
        std::cout << a[i] << ' ' << name[i] << '\n';
    }
}

int main()
{
    A x;

    x.read();
    x.display();
}
main()

C++ does not support implicit int. If you want your code to be compilable on another compiler, you need to specify the int explicitly:

int main()
{
    // add an explicit return for nonstandard compilers
    return 0;
}

Thank u so much....for ur response....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.