Variable and file type to make file

Hey everyone,
I'm trying to make files by what user has input. my code makes files but it doesn't have an extension like, .txt .dat or whatever.
can you please help what should I do here.

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

int main()
{
	char name[20];
	int HowManyStudents = 0;
	
	cout<<"How many students do you have? ";
	cin >> HowManyStudents;
	
	for (int i=0; i<HowManyStudents ; i++)
	{
		cin >> name;
		ofstream fout (name);
		fout << name;
		fout.close();
	}
}
Hello Hassibayub,

It would be much easier if you used a std::string in place of the character array then on line 16 all you would have to do is ofstream fout (name + ".txt");.

From C++11 standards on you can use a std::string for the file name.

You would also have to include "<string>" header file and change line 7 to std::string name;.

Hope that helps,

Andy
I have done what you said... I'm using dev c++5.11

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
using namespace std;

int main()
{
	std::string name;
	int HowManyStudents = 0;
	
	cout<<"How many students do you have? ";
	cin >> HowManyStudents;
	
	for (int i=0; i<HowManyStudents ; i++)
	{
		cin >> name;
		ofstream fout (name + ".txt");
		fout << name;
		fout.close();
	}
}


But it shows error:
line:18 col:31

[Error] no matching function for call to 'std::basic_ofstream<char>::basic_ofstream(std::basic_string<char>)'
You need to set the compiler option -std=C++11 in your IDE
or
try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
using namespace std;

int main()
{
	std::string name;
	int HowManyStudents = 0;
	
	cout<<"How many students do you have? ";
	cin >> HowManyStudents;
	
	for (int i=0; i<HowManyStudents ; i++)
	{
		cin >> name;
                string fname = name + ".txt";
		ofstream fout (fname.c_str());
		fout << name;
		fout.close();
	}
}
It works...Thank you very much @thomas1965.
I don't have much information about setting up IDE...
so..
which one is the best standard and IDE?
I think for the beginning Dev C++ is ok. Here is how to set the compiler options.
http://www.cplusplus.com/doc/tutorial/introduction/devcpp/

Personally I prefer Visual Studio but it's a bit complicated, especially the templates are too sophisticated for beginners. Other IDEs are Code::Blocks, CodeLite or C++Builder Starter.
Topic archived. No new replies allowed.