Reputation: 17
FYI I'm a beginner in C++. This is just a part of the complete code, the problem is the 'student.id', if the input starts with '0' e.g.'06042010', the output shows no zero(in this case would be '6042010'! And the point is, I want that first zero to be shown. Thanks.
#include<iostream>
using namespace std;
struct students
{
char name[15];
char surname[10];
int id;
};
int main()
{
students student;
cout<<"Name: ";
cin>>student.name;
cout<<"Surname: ";
cin>>student.surname;
cout<<"ID: ";
cin>>student.id;
cout<<"\nStudent: "<<student.name<<" "<<student.surname<<" ID "<<student.id<<endl;
return 0;
}
Upvotes: 1
Views: 118
Reputation: 302
If you need or want to keep the student id a number for some reason you can also us the following:
#include <iomanip>
const int width = 8; //The length of your student ID numbers
cout << "\nStudent: " << student.name << " " <<student.surname
<< " ID " << setfill('0') << setw(width) << student.id << setfill(' ') << endl;
If your ID numbers are not all the same length you will have to detect how long they are and use the appropriate width in each setw() call.
Upvotes: 0
Reputation: 46259
If your IDs will always be a particular length, you can use C's printf
function instead of streams, which gives you more power;
printf( "Student: %s %s ID %08d\n", student.name, student.surname, student.id );
That will always print 8 digits of ID, and will prefix with 0s as needed (if it was just %8d
it would prefix with spaces).
But as already pointed out, you're likely better off storing it as a string, because then you will be able to increase the length of the IDs in the future without needing to adjust all the old IDs.
Upvotes: 1
Reputation: 500377
If you need to preserve leading zeros, you should store id
as a string and not an int
.
Upvotes: 5