2017-11-18 1 views
0

Ich versuche, eine Dezimal-Nr. im folgenden Format: "##### + 3.01" Fall: Es gibt eine Dezimalzahl nein (sagen wir 3,01 in diesem Fall). Ich muss es mit seinem Vorzeichen +/- vor dem y no drucken. von #, mit einiger fester Gesamtbreite. (Sagen wir in diesem Fall x = 10).Drucken Sie eine Dezimalzahl in einem bestimmten Format mit Setfill() in C++

Ich habe versucht, so etwas tun:

double no = 3.01; 
    cout << setfill('#') << setw(10) ; 
    cout << setiosflags(ios::showpos); 
    cout << fixed << setprecision(2) << no << endl; 

Aber ich bin immer followinfg Ausgabe:

+#####3.01 

Erwartete Ausgabe:

#####+3.01 
+2

Mögliche Duplikat [? Std :: Ostringstream setzt Zeichen in falschen Ort] (https://stackoverflow.com/questions/ 46729847/stdostringstream-puts-sign-in-false-location) – Barmar

Antwort

0

Ihr Code gab mir korrekte Ergebnisse. Ich benutze eine Linux-Maschine.

Gerade falls es ein OS abhängig Problem ist, versuchen Sie diesen Code:

#include <iostream> 
#include <iomanip> 

using namespace std; 

int main() 
{ 
    double no = 3.01; 
    cout << setfill('#') << std::right<< setw(10) ; 
    cout << setiosflags(ios::showpos); 
    cout << fixed << setprecision(2) << no << endl; 
} 
+0

Es hat funktioniert. Vielen Dank. –

Verwandte Themen