cout in Variable 'umleiten' ???
-
--------------------------------
Windows XP
Konsolenanwendung
Sprache: C++
Programm: Visual C++ 6
--------------------------------Hallo, ich habe folgendes Problem.
Ich habe zwei zahlen. Die wie als würde ich sie in cout ausgeben in einer Variable gespeichert werden sollen.
Mal ein Beispiel:
#include <iostream> using namespace std; int x = 3, y = 4; int main() { cout << x << y << endl; // Ausgabe: 34 return 0; } /****** Anstatt auf der Konsole soll die zahl ‚34’ jetzt in einer Variable stehen ******/
Kann ich den Datenstrom von cout in eine Variable ‚umleiten’?
Wäre nett, wen jemand ein Beispiel häte…
Gruß,
Dino
-
wenn du unbeding operator<< benutzen willst dann: http://www.cplusplus.com/ref/iostream/stringstream/
ansonsten: http://www.cplusplus.com/ref/cstdio/sprintf.html
-
hm, so zum bleistift?
#include <iostream> struct mycout { int val; int mul; mycout() : val(0), mul(1) {} void operator<<(int i) { val += mul * i; mul *= 10; std::cout << val << std::endl; } }; int main() { mycout cout; cout << 2; cout << 3; }
-
...?
Also mit dem Operator "<<" würde ich es schon gerne machen. Auf der Seite finde ich mich allerdings nicht zrecht...
Kannst du mir nicht ein Beispiel geben?
Und cout23, nichts für ungut, aber da blicke ich nicht durch...
-
int x = 3, y = 4; string s; stringstream ss; ss << x << y; ss >> s; // in s steht jetzt '34' cout << s << endl; // ausgabe zum testen
-
naja, das ist halt ne klasse (bzw. nen struct), dass den operator << implementiert und ihn nutzt, um eine interne variable in der gewünschten weise zu setzen.
mul sorgt schlicht dafür, dass die zahl auch an die richtige stelle rutscht.
wenn man aus der funktion mycout& operator<<(int i) macht und ans ende noch ein return *this setzt, kann man sogar sowas wie mycout << 2 << 3 << 4 ... machen.
aber wahrscheinlich bist du mit stringstreams besser aufgehoben.