Splitting file into two separate ones.

This is my input.txt
1
2
3
4
Computer 7
Biology 8
Computer 11
Biology 12

I want to split that into 2 different files each file with the same category so that in the end bio.txt would contain only Biology 8 and Biology 12. Same with comp.txt.

This is what I have so far, not sure how to fix it, any help would be greatly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;

int main()
{

	ifstream in;
	in.open("input.txt");
	if(in.fail())
		exit(0);

	ofstream comp;
	comp.open("comp.txt");
	ofstream bio;
	bio.open("bio.txt");

	string name, biology, computer;
	int no;

	while(!in.eof())
	{
		in >> name >> no;

		if(strcmp(name,biology)==0)
			bio << name << no;

		else if(strcmp(name,computer)==0)
			comp << name << no;

		else
			continue;
	}

	in.close();
	comp.close();
	bio.close();

	system ("pause");
	return 0;
}
You're giving strcmp's second parameter an empty string. You define biology, and computer but don't put anything in them.

Also, prefer std::string::find over strcmp:
 
if(name.find("Biology") != std::string::npos) //"Biology" was found in 'name' 

Also note that strings are case sensitive.
@huynher:
1. I ran this and got an error because I didn't have:
#include <cstdlib>

2. Don't do strcmp with C++ string, I also recommend using the string compare method: http://www.cplusplus.com/reference/string/string/compare/

3. You didn't initialize biology, and computer (as Thumper said).

4. You also did not consider case sensitivity, so this won't even always work. Use the string lower function.

5. After I fixed all the other mistakes (except case sensitivity), there was also a lacking newline character in the output as well as a space between the number and the name.

Here is the result:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

int main( void ){
	ifstream in;
	in.open("input.txt");
	if(in.fail())
		exit(0);

	ofstream comp;
	comp.open("comp.txt");
	ofstream bio;
	bio.open("bio.txt");

	string name, biology="Biology", computer="Computer";
	int no;
	
	while(!in.eof())
	{
		in >> name >> no;

		//if(strcmp(name,biology)==0)
		if( name.compare(biology) == 0 )
			bio << name << " " << no << "\n";

		//else if(strcmp(name,computer)==0)
		if( name.compare(computer) == 0 )
			comp << name << " " << no << "\n";

		else
			continue;
	}

	in.close();
	comp.close();
	bio.close();

	system ("pause");
	return 0;
}
Last edited on
Ah okay, thank you guys very much!

I'm new to programming and I haven't been taught these different methods in my class.
Good luck! Keep having fun programming :).
Topic archived. No new replies allowed.