1

I've looked around and I haven't found a good answer.

I have files like this: text1.txt text2.txt text3.txt

user wants to specify which file to open:

int x;
string filename;
cout << "What data file do you want to open? (enter an int between 1 -> 3): ";
cin >> x;
filename = "P3Data" << x << ".txt" ; //does not compile

myfile.open(filename);

What is the proper way to do this?

2 Answers 2

5

To use the streaming interface, you need a stringstream:

std::ostringstream filename;
filename << "P3Data" << x << ".txt";

myfile.open( filename.str().c_str() );

Otherwise, you can concatenate two strings using +.

Sign up to request clarification or add additional context in comments.

3 Comments

If myfile is an ifstream, I suppose you might want filename.str().c_str().
@Vlad: Unless this is C++11. Anyway .c_str() will work in both C++03 and C++11.
I didn't know they fixed it. Thanks!
1

In C++11, you can say it like this:

#include <string>

const std::string filename = std::string("P3Data") + std::to_string(x) + std::string(".txt");

If you don't have C++11, you can use boost::lexical_cast, or string streams, or snprintf. Alternatively, you could just read from std::cin into a string rather than an integer.

(If you read into an integer, surround the read with a conditional check to verify the operation: if (!(std::cin >> x)) { /* error! */ }

1 Comment

Glad you edited that. I was just about to try that funny << syntax on a C++11 compiler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.