penu
penu

Reputation: 1040

C++ - Concatenating strings (like PHP?)

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?

Upvotes: 1

Views: 134

Answers (2)

K-ballo
K-ballo

Reputation: 81399

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 +.

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477512

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! */ }

Upvotes: 1

Related Questions