#include <cstdlib>
#include <iostream>
#include <cstring>
#include <fstream>
#include <sstream>
usingnamespace std;
int main(int argc, char *argv[])
{
ofstream out("all.txt");
for (int i=1; i<154; i++) {
string s_line;
char* s_file;
// here the missing code to change integer i into the char s_file
// ??????????????
ifstream in(s_file);
while (getline(in, s_line)) {
out << s_line << "\n";
}
}
return 0
}
I put into the missing part of the code some functions changing integer into char (or string) in many different ways but nothing worked. Now I am going to try to use iterators but the solution seems so simple that I am asking for any help!
Try int(s_file);. I'm not sure about C-strings but it works for normal char-int conversion.
Edit: I just realised you want to put i into the character string.
Here's how: s_file = ("%d", i);
You need to use string formatting, like you would in printf();.
%d is decimal formatting, the integer is in base-10 (decimal) and therefore it's %d.
How big are the files? I found that when trying to merge large files, fstream:: couldn't handle them (they were half a GB each, mind) and ended up writing a batch file.
Thank you for your help. But chrisname, your instruction seems not to work. Gregor, your solution works but I am not sure whether the instruction s_file[0]='\0' is necessary. Here is the code that works ok:
#include <iostream>
#include <cstring>
#include <fstream>
usingnamespace std;
int main(int argc, char *argv[])
{
ofstream out("all2.txt");
char* s_file = newchar(16);
for (int i=1; i<154; i++) {
string s_line;
//s_file[0]='\0'; - is this really needed?
sprintf(s_file, "%d", i);
ifstream in(s_file);
while (getline(in, s_line)) {
out << s_line << "\n";
}
}
return 0;
}
I must confess that I managed to solve the problem before but in a not very elegant way. I used Excel to produce 153 copies of the three lines of instructions:
1 2 3 4 5 6 7
ifstream in1("1");
while (getline(in1,s)) out << s << "\n";
in1.close();
ifstream in2("2");
while (getline(in2,s)) out << s << "\n";
in2.close();
........
...and it worked.
I hope that there is another - pure C++ - solution to this.
Thanks, it works perfectly! Here is the whole program I checked:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <fstream>
#include <sstream>
#include <string>
usingnamespace std;
int main()
{
ofstream out("outputfile.txt");
string line;
for (int i=1; i<5; i++) {
stringstream filename;
filename << i << ".txt";
ifstream in( filename.str().c_str() );
while (getline(in, line)) {
out << line << "\n";
}
}
return 0;
}
I changed here the "ostringstream filename;" into "stringstream filename;" - have no idea what the difference is. Another unclear point for me is the double usage of "str-like" functions in "filename.str().c_str()". But I think I will find the answer soon. Thanks again!