improper assignment of values to struct members

Hi, I want to get info on employee code,name, age, salary from the user and store it into a struct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
main()
{
 struct person
 {
  char empcode[5];
  char name[20];
  int age;
  float sal;
 };
 
person p;

cout<<"Enter the following details";
cout<<"Code:";
cin>>p.empcode;
cout<<"Name:";
cin>>p.name;
cout<<"Age:";
cin>>p.age;
cout<<"Salary:";
cin>>p.sal;

cout<<"\n"<<p.empcode<<"\t"<<p.name<<"\t"<<p.age<<"\t"<<p.sal<<"\n";

getch();
}


I run this code and I enter the values :-
Code - QWE23
Name - POOJA
Age - 18
Salary-230.5

But what the output shows is :-
p.empcode ---> QWE23POOJA
p.name ---> POOJA
p.age ---> 18
p.sal ---> 230.5

Can somebody help me?
empcode is declared as 5 characters. Since these are C strings, each C string must be terminated by a null character. You inputted 5 characters. Consequently, there was no place to store the null character. When you went to print empcode, it printed until it found a null character (which was at the end of POOJA).

Solution: Use C++ std::string instead of C strings.

BTW, main() must be type int.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <string>
#include <iostream>
using namespace std;

int main()
{
 struct person
 {  string empcode;
    string name; 
    int age;
    float sal;
 };
...

"Since these are C strings, each C string must be terminated by a null character. You inputted 5 characters. Consequently, there was no place to store the null character."

Thanks a ton! This was the mistake I made....I changed the declaration to :

char empcode[6];

and it worked!

However, I also tried declaring empcode as a string...but it showed error while compiling.



(Note: I did include <string> header)
I also tried declaring empcode as a string...but it showed error while compiling.

What error?
Topic archived. No new replies allowed.