Integer Formatieren

FiS

Grünschnabel
Hi,

ich habe eine int variable in c++

z = 56;
im zweiten durchlauf
zB z=4

möchte nun als ergebniss immer 4 stellen haben

also

z = 0056
und
z= 0004

wie stelle ich das an?
 
In C++:

Code:
#include <iostream>

using namespace std;

int main(){

        int n = 9;
        cout.width(4);       
        cout.fill('0');      
        cout <<  n << endl;  
        return 1;
}
 
Oder nochmal C++:

Code:
#include <iostream>
#include <sstream>

using namespace std;

int main(){

        int n = 9;

        ostringstream os;
        os.width(4);
        os.fill('0');
        os << n;
        
        string verwendung = os.str();
        cout <<  verwendung << endl;  
}
 
P.S.

Ein OO Ansatz währe vielleicht noch das Überladen des Cast Konstruktors
und eine eigene Integer Klasse.

Ungefähr so:

Code:
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

class FormatedInteger{

        private:
                int value;
                int width;
                ostringstream os;
        public:
                FormatedInteger(int val, int w = 4):value(val), width(w){}

                operator string(){
                        os.width(width);
                        os.fill('0');
                        os << value;
                        return os.str();
                }
};
        
int main(){

        FormatedInteger n(9, 4);
        cout << (string)n;
}
 
Zurück