If I create a map for names and birthdays. When i enter birthdates that end in 0 it changes it the number to an octal. how do i print out the birthday ie 010525
== 4437
so when i call it -> second
it will print 010525
#include <stdio.h>
#include <iterator>
#include <string>
#include <map>
#include <iostream>
using namespace std;
int main(){
map<string, int>birth;
birth["Chicken"] = 010525;
birth["Dragon"] = 010266;
map<string, int>::iterator it;
for(it = birth.begin() ; it != birth.end(); it++){
cout << it -> first + " ";
cout << it ->second << endl;
}
}
Output:
Chicken 4437
Dragon 4278
There are 2 ways to fix this problem:
(1) The first way is to enter the birthday without the leading 0 as follow:
birth["Chicken"] = 10525;
birth["Dragon"] = 10266;
Then use setfill()
and setw()
to fill the leading 0.
Please note that the code that uses std:setw() and std::setfill() will compile only with new C++ compiler versions such as C++14 (or C++11)
#include <stdio.h>
#include <iterator>
#include <string>
#include <map>
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
map<string, int>birth;
birth["Chicken"] = 10525;
birth["Dragon"] = 10266;
map<string, int>::iterator it;
for(it = birth.begin() ; it != birth.end(); it++){
cout << it -> first + " ";
cout << setfill('0') << setw(6) << it ->second << endl;
}
}
(2) The second way is to store the birthday as string. This way you can enter the birthday with the leading 0.
Here is the code:
#include <stdio.h>
#include <iterator>
#include <string>
#include <map>
#include <iostream>
using namespace std;
int main(){
map<string, string>birth;
birth["Chicken"] = "010525";
birth["Dragon"] = "010266";
map<string, string>::iterator it;
for(it = birth.begin() ; it != birth.end(); it++){
cout << it -> first + " ";
cout << it ->second << endl;
}
}