CrazyBacon
CrazyBacon

Reputation: 55

C++ filestream: Created filename ends with weird symbols

So I have been working with the filestream and i came up with a problem. Every time i try to save a file, the name of the created file ends with these two characters: i' . Is there any way to fix this?

Here is what I get:

Capture

Here is my code:

    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <stdlib.h>
    #include <windows.h>
    #include <cstdlib>
    #include <stdio.h>
    #include <cstdio>
    #include <fstream>

    using namespace std;

    string p = "";
    string some_string;

    char o[20];

    int _tmain(int argc, _TCHAR* argv[])
    {
        cout << "Choose a name for your file: ";

        getline(cin, p);

        if (p.length() >= 20)
        {
            cout << "Max character length: 20 characters\n\n";
            system("pause");
            exit(EXIT_SUCCESS);
        }
        else
        {
            ofstream out("resources");
            out.trunc;
            out << p;
            out.close();
        }

        for (int i = 0; i < 20; i++)
        {
            o[i] = ' ';
        }

        for (unsigned int t = 0; t < p.length(); t++)
        {
            o[t] = p.at(t);
        }

        ofstream save(o);

        save << some_string;

        save.close();

        cout << "A new file named: '" << p << "' was created\n";
        Sleep(2500);

    }

(I use Microsoft VS 2013)

Thanks in advance!

Upvotes: 0

Views: 477

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

You're pre-initialising o to all spaces, but that's useless. What you should be doing is writing a '\0' to the character after your filename's final character. Otherwise the array is non-terminated and you may get "garbage" at the end when you use it as a C-string.

So:

for (unsigned int t = 0; t < p.length(); t++) {
    o[t] = p.at(t);
}

o[p.length()] = '\0';

You should also change your error message to the following, to make it accurate:

cout << "Max character length: 19 characters\n\n";

It would be much easier if you used a std::string for o, then you wouldn't have to mess about with char arrays and loops at all. In fact, since o is just a copy of the characters within p, you can forget o entirely and just use p itself:

ofstream save(p);

That said, in C++03, you may have to obtain a C-string from p because the ofstream constructor didn't accept std::string yet:

ofstream save(p.c_str());

(I don't remember but I think MSVS allowed the std::string argument anyway.)

Upvotes: 1

Related Questions