[ask]read file with loop in C++

hellow all,

iam beginner in c++ i have problem like this:

input.txt
1
2
3
alex
donny
ruby


so i want loop how to c++ can read input.txt and create file with they name like this:

alex.txt
donny.txt
ruby.txt


thx for your advice
First of all, if you're not familliar with std::ifstream and std::ofstream, read this:
http://www.cplusplus.com/doc/tutorial/files/
If you know it already, or after you read it, you should know what this does:
1
2
3
4
5
6
7
8
9
10
char* name;
ifstream fin("input.txt");
int i=0;
ofstream* fout=new ofstream[1];
while(fin>>name)
{
      fout[i]=ofstream(name);
      ++i;
      fout=new ofstream[i+1];
      }

I'm just not sure about the new part, but it might work.
@viliml
thx for your comment

i found script like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// ifstream::is_open
#include <iostream>
#include <fstream>
using namespace std;

int main () {

  ifstream infile;
  infile.open ("sample");
  if (infile.is_open())
  {
    while (!infile.eof())
      cout << (char) infile.get();
    infile.close();
  }
  else
  {
    cout << "Error opening file";
  }
  return 0;
}


so output like this

1
2
3
alex
donny
ruby


but i want output like this

1
2
3
alex_sample1.txt
donny_sample1.txt
ruby_sample1.txt


so how i can create output like that with newfile
Yeah, you need to make them strings, and then use the c_str() for the ofstream. Let me try it on my comp, and I'll let you know.
OK, I think this is the only way:
1
2
3
4
5
6
7
8
string name;
	int i=0;
	ifstream fin("input.txt");
	while(fin>>name)
	{
      	ofstream fout((name+"txt").c_str());
        // do stuff with that file now;
      }
@viliml: you've got memory leaks.
As streams don't have a copy constructor you'll need to use pointers with an stl container (c++0b resolves that with an emplace_back)

But I don't actually understand the assignment. If you only want to create the files, then you could use
1
2
while( input>>file_name )
  ofstream( (file_name+".txt").c_str() );


By the way you shouldn't loop on eof (you check for failure too late)
1
2
3
4
5
6
7
8
9
       string name;
	ifstream fin("example.txt");
	vector<ofstream*> fout;
	while (getline(fin, name))
	{
      	        cout<<name<<endl;
		ofstream temp(name+".txt");
		fout.push_back(&temp);
      	}

This should work with c++11, if not just replace line 7 with what ne555 said.
You are taking the address of a temporary there, your pointers are invalid.

With c++0b I think it would be
1
2
vector<ofstream> fout;
fout.emplace_back( (name+".txt").c_str() );
but I can't make it compile.
It seems that the problem is with vector and its reallocation. It works with list
Topic archived. No new replies allowed.