2

I am trying to replace characters badSymbols to goodSymbols in my text file, but it adds one more character to my replacing character. For example, when I replace 'æ' with 'c', I get 'Ãc'.

This simple program reads text file line by line and replaces characters, then writes it in "fileout.txt"

int main()
{
    char buffer, c;
    string line, filepath;
    fstream filein, fileout;
    char badSymbols[] = {'', 'ê', '³', 'æ', '', '¹', '¿', '£', '', '³', ''};
    char goodSymbols[] = {'s', 'e', 'l', 'c', 'z', 'a', 'z', 'L', 's', 'l', ''};
    string symbol;
    size_t found;
    cout << "Podaj sciezke pliku, w którym zamienic znaki" << endl;
    cin >> filepath;
    filepath = filepath + ".txt";
    filein.open("/home/damian/jezykc++/untitled2/gared.txt", ios:: in );
    fileout.open("/home/damian/jezykc++/untitled2/fileout.txt", ios::trunc | ios::out);
    if (filein.good() == true)
    {
        std::cout << "Uzyskano dostep do pliku!" << std::endl;
        while (getline(filein, line))
        {
            // buffer=line;
            //getline(filein,line);
            for (int i = 0; i < sizeof(badSymbols); i++)
            {
                symbol = goodSymbols[i];
                found = line.find(badSymbols[i]);
                if (found != std::string::npos)
                    line.replace(found, 1, symbol);
            }
            cout << line << endl;
            fileout << line << endl;
        }
    }
    else std::cout << "Dostep do pliku zostal zabroniony!" << std::endl;
    return 0;
}
David G
  • 94,763
  • 41
  • 167
  • 253
  • 1
    Have you ruled out problems related to encoding, wide characters? – Brian Cain Dec 19 '14 at 21:18
  • This is almost certainly an encoding problem. Here's (just one) reference http://stackoverflow.com/questions/17648966/handling-non-ascii-chars-in-c – Falmarri Dec 19 '14 at 21:19

1 Answers1

0

you can use file.get() instead of getline() in while. I think it would be better if you get only one character and compare it with "bad characters". in the other word, use strcmp() for converting your characters in your code!

0bijan mortazavi
  • 356
  • 4
  • 13