Need Small Help writing file

Hi guys, please overview my code below. I need help by creating the output of this code to a txt file.. or may be excel(if possible) ..

*****************************************************************
#include <iostream>
#include <stdlib.h>
#include <string>
#include <sstream>
using namespace std;

string *Random() {
string *code = new string;
code->append("CR");
int randomnumber = rand();
ostringstream converter;
converter << randomnumber;
code->append(converter.str());
code->append("NQ");
return code;
}

int main() {
string *newcode;
int index;
for(index=0; index < 10; index++) {
newcode = Random();
cout << *newcode << rand() % 1000 << endl;
}
system("PAUSE");
return 0;
}
*******************************************************
http://www.cplusplus.com/doc/tutorial/files/

add fstream fout("test.txt"); at the beginning,

change cout << to fout <<,

add fout.close(); at the end.


By the way, your code could be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <stdlib.h>
#include <string>
#include <sstream>
using namespace std;

string Random() {
   string code = "CR";
   int randomnumber = rand();
   ostringstream converter;
   converter << randomnumber;
   code += converter.str() + "NQ";
   return code;
}

int main() {
   for(int index=0; index < 10; index++)  
      cout << Random() << rand() % 1000 << endl;
   system("PAUSE");
   return 0;
}
There is no reason to use pointers. you don't have to write "append" when a + operator is overloaded. You don't have to use variables to store what functions return.
Actually you don't need to do that string composition thing. You could just write
cout << "CR" << rand() << "NQ" << rand()%1000 << endl;

As for excel, look into csv ( http://en.wikipedia.org/wiki/Comma-separated_values ) files. Excel should open that.
Topic archived. No new replies allowed.