Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ create string of text and variables

I'm trying to do something very simple and yet, after an hour of so of searching a I can't find a suitable answer so I must be missing something fairly obvious.

I'm trying to dynamically create filenames for use with ifstream. Whilst I understand various methods are available of doing this, I have settled on creating a std::string, and the using stringname.c_str to convert to const.

The problem is however that I need to create the string with a mix of variables and predefined text values. I'm getting compiler errors, so this must be a syntax issue.

Pseudo

std::string var = "sometext" + somevar + "sometext" + somevar; 

Thanks!

like image 640
Jack Farrow Avatar asked Apr 18 '12 22:04

Jack Farrow


2 Answers

Have you considered using stringstreams?

#include <string> #include <sstream>  std::ostringstream oss; oss << "sometext" << somevar << "sometext" << somevar; std::string var = oss.str(); 
like image 108
mgiuffrida Avatar answered Sep 20 '22 17:09

mgiuffrida


In C++11 you can use std::to_string:

std::string var = "sometext" + std::to_string(somevar) + "sometext" + std::to_string(somevar);   
like image 20
David Rinck Avatar answered Sep 19 '22 17:09

David Rinck