Monday, 15 June 2015

Redirect cout to file c++ -



Redirect cout to file c++ -

i have problem code. has been little school project, wish enhance redirecting strings console window, ".txt" file. problem lastly string printet. guess maintain overwriting coolnumber.txt file, cannot see create change, don't overwrite, add together file.

my code looks following:

#include <iostream> #include <string.h> #include <sstream> #include <fstream> using namespace std; string inttochar[10] = { "0", "1", "2abc", "3def", "4ghi", "5jkl", "6mno", "7pqrs", "8tuv", "9wxyz" }; void coolnumber(string number, string character) { ofstream file; file.open("coolnumber.txt"); streambuf* sbuf = cout.rdbuf(); cout.rdbuf(file.rdbuf()); if (number == "") { cout << character << ", " << endl; } else { int length = inttochar[number[0]-'0'].size(); (int = 0; < length; i++) { stringstream ss; char c = inttochar[number[0]-'0'][i]; string s; ss << c; ss >> s; coolnumber(number.substr(1, number.size()), character + s); } } } int main() { string number = "27529250"; cout << "type mobilenumber: "; cin >> number; //int length = inttochar[5].length(); //cout << length << endl; coolnumber(number, ""); }

i know code works cout console window, if written without code

ofstream file; file.open("coolnumber.txt"); streambuf* sbuf = cout.rdbuf(); cout.rdbuf(file.rdbuf());

it awesome code work.

p.s. have tried looking @ other topics here on stackoverflow, can't seem find works improve me.

you seek stream version of appending file

file.open("coolnumber.txt", std::ofstream::app)

c++ redirect cout

No comments:

Post a Comment