some problems this text cleaning program

hello everyone, what this program is supposed to do is to get text from a file and remove all weird characters (1234567890!@$#%^&*) and then output the cleaned text to the same file (cleaning it). for example if a file had the text

(@#%$hello(@#%( *)@#*%wor(%$@ld()#Q%

the file should be rewritten to say

hello world

here is my code
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	string filename = "C:\\Users\\Matt\\Desktop\\c++ text files\\info.txt";
	fstream myFile;
	
	
	//getline(cin,filename);
	myFile.open(filename);
	
	if(myFile.fail())
	{
		cout<<"fail";
		exit(1);
	}
	string text;

	while(!myFile.eof())
	{
		myFile >> text;
		int s = text.length();
		int pos = 0;
		//cout << s << endl;
		//cout << text << endl;
		for (int i = 0; i < s; i++)
		{
			
			char check = text.at(pos);
		    //cout << check << endl;
			//cout << i << endl;
			int num = (int) check;
			//cout << num << endl;
		if (num > 90 && num < 97)
		{
			text.erase(pos,1);
		}

		check = text.at(pos);
		num = (int) check;

		if (num > 64 && num < 123 )
		{
		pos++;
		}
		else
		{
		text.erase(pos,1);
		}

		}
		
		cout << text << " ";
		ofstream file2;
		file2.open(filename);
		file2 << text << endl;
		

	}
	
	myFile.close();
	//exit(1);




	return 0;
}


there are 2 problems with this program i cant figure out

1. if i flood the file with enough characters (not sure if letters or special characters causes it) i start getting a ton of errors while the program runs, whats weird is if i keep clicking continue on the errors the text will still get cleaned correctly

2. my second problem is getting the clean text to output correctly to the file, my algorithm for cleaning seems to work fine but i cant figure out how to correctly write the cleaned text to the file without messing it up.

any help would be appreciated thanks.
Read the characters one at a time, rather than using a string.

By wierd character, I assume you mean non-alpha/non-numeric chars. What about space?

You can use isalpha(), isnum() to filter out alpha and/or numeric chars. Write those out and ignore the rest.

You don't need to call open/close on a file stream, that's implicit. You can pass the filename to the constructor as in:
 
    ofstream file2(filename.c_str());

to read 1 char at a time does the only thing that needs to be done is change text to a char variable?

the only chars that should be kept are letters and spaces

and im still not sure how to properly output the chars to the file in such a way there is no loss of data (the algoithim does not get confused)
Topic archived. No new replies allowed.