Well, I am making a tic-tac-toe game, and I need a way to make it so when the person enters their name it adds a ".txt" to the end of their name.

For example:
What is your name?
Robert

*ifstream infoout("Robert.txt");*

The .txt highlighted in red is what I need to add to the name..

Recommended Answers

All 6 Replies

std::string name;

// Get the name...

std::ifstream in ( ( name + ".txt" ).c_str() );

If the name is being read in as a string, you can append to it using the + operator:

std::string name;
std::cin >> name; /*say, Robert */
name += ".txt."
std::cout << name << std::endl; /* should print Robert.txt */

EDIT: And then you can open the file as described above...

Thanks for the input, however I get the error of:

1>.\blah.cpp(83) : error C2678: binary '+' : no operator found which takes a left-hand operand of type 'void (__cdecl *)(void)' (or there is no acceptable conversion)
1>        could be 'built-in C++ operator+(volatile const System::Object ^, volatile const System::String ^)'
1>        or       'built-in C++ operator+(volatile const System::String ^, volatile const System::Object ^)'
1>        or       'built-in C++ operator+(volatile const System::String ^, volatile const System::String ^)'
1>        while trying to match the argument list '(void (__cdecl *)(void), System::String ^)'
1>.\blah.cpp(83) : error C2228: left of '.c_str' must have class/struct/union

Here is the code that I added to it:

void predata()
{
    ifstream infoout( ( name1 + ".txt" ).c_str() );
    if (infoout.is_open())
    {
        infoout >> timeseasy[0];
        infoout >> timeseasy[1];
        infoout >> timeseasy[2];
        infoout >> timesmedium[0];
        infoout >> timesmedium[1];
        infoout >> timesmedium[2];
        infoout >> timeshard[0];
        infoout >> timeshard[1];
        infoout >> timeshard[2];
        infoout.close();
    }
}

*Also, I probably should have mentioned this earlier. I am using Visual C++*

If the name is being read in as a string, you can append to it using the + operator:

std::string name;
std::cin >> name; /*say, Robert */
name += ".txt."
std::cout << name << std::endl; /* should print Robert.txt */

EDIT: And then you can open the file as described above...

Yes, that works, however, when I try to open a file saying:
ifstream infoout(name1);
it gives me errors. :(

Edit: aCtually, I just combined both of your codes, and it works perfectly. Thanks, both of you!! :)

You need to use c_str as described above:

ifstream in (name1.c_str());

>I am using Visual C++
More specifically, it looks like you're using C++/CLI. I don't recommend mixing standard C++ libraries (such as ifstream) and .NET libraries (like System::String). It's more of a headache than it's worth, if you can avoid it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.