Kama
Kama

Reputation: 39

C++ writing strange symbols instead of characters

New to this forum so I hope my formatting is okay.

The following is meant to iterate over the strings (sections) in a .txt, then run a function nuc() on each character in the string (section). nuc() on each character either adds the character to the string called fragment, or adds a period ".". If nuc is executed on the end of a string, it should write fragment to the text file "fragments.txt". Because nuc is executed within itself, it starts by shortening the fragment to the position on which nuc is being executed.

Unfortunately when I execute the code it doesn't seem to write the characters, instead writing bizarre symbols (rotated L's or playing card suits). Should I use something other than a string? This is essentially translated from python so you can imagine the oversights I'm capable of.

I've learned most of this over the last two days so I apologize in advance if its a really silly oversight. I suspect it may be due to the way I've initialized my nuc function, or the way I've called it.

I appreciate any help in advance. I suspect my code is painful to look at.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

ifstream sections("sections.txt");
ofstream fragments("fragments.txt");
string fragment;


void nuc(string section, int position)
{

    for (int i = 0; i <= 1; i++)
    {
        fragment.resize(position);
        cout << i << endl;
        if (i == 0)
        {
            fragment += ".";
        }
        else if (i == 1)
        {
            fragment += position;
        }

        try
        {
            section.at(position + 1);
            nuc(section, position + 1);
        }

        catch (exception out_of_range)
        {
            fragment += "\n";
            fragments << fragment;
        }

        cout << fragment << endl;
    }
}

int main()
{
    string section;
    int pos = 0;

    while (getline(sections, section))
    {
        nuc(section, pos);
    }

    sections.close();
    system("pause");
    return 0;
}

EDIT: alright i got it to run by switching fragment += position to fragment += section.get(position) (smh). Now it seems I can fragment longer strings than I could in python, but it still takes very long. Can anyone offer any recommendations to optimize the code to make it run faster, e.g. if using iterators rather than strings to get(position) might make it run faster? Otherwise perhaps a resource that could help me learn about optimizing code with these basic functions?

Upvotes: 1

Views: 1647

Answers (1)

Killzone Kid
Killzone Kid

Reputation: 6240

The reason you see lots of weird characters is because of

fragment += position;

fragment is a string, position is an int. When you add int to string it is treated as a char created from int code, and many of those chars at the start of ASCII table are not even printable. See for yourself

Upvotes: 2

Related Questions