Jump to content

  • Log In with Google      Sign In   
  • Create Account


Variables within strings? (C++)


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
23 replies to this topic

#1 Youbar   Members   -  Reputation: 122

Like
0Likes
Like

Posted 01 December 2012 - 03:36 AM

I'm just going to get straight to the point:
Using "cout", I can get text, then a variable, then some more text. I wondered if I could replicate that into a string?
e.g
cout << "Hi, I am " << x << "years old."; into a string.

EDIT: I've tried something with a string, but I've gotten a compile error:
invalid operands of types `const char[22]' and `int' to binary `operator<<'

The string is as follows:
string day1_c_1 = "You, along with your " << rs_q_c << " friends, set up camp outside of town. You carried " << rs_q_f << " units of food with you, along with another " << rs_q_m << " units of metal.";

Edited by Youbar, 01 December 2012 - 03:44 AM.


Sponsor:

#2 Sparkon   Members   -  Reputation: 380

Like
0Likes
Like

Posted 01 December 2012 - 04:06 AM

I might have misunderstood your question.. But are you asking for a way to concatenate strings and variables together? If so : yes you can!
If the variable is of type string you can do :
std::string s = "hi" + yourstring;

Otherwise .. If it is a number you have to cast it to a string before.

EDIT : the c++ way to convert numbers to integers is the stringstream (just google it ). I'm writing from phone :(

#3 Youbar   Members   -  Reputation: 122

Like
0Likes
Like

Posted 01 December 2012 - 04:14 AM

string day1_c_1 = "You, along with your " << rs_q_c << " friends, set up camp outside of town. You carried " << rs_q_f << " units of food with you, along with another " << rs_q_m << " units of metal.";

The variables rs_q_letter is a number. I'm wondering if I could pack them all into a sentence like the above, which produces a compile error, or do I have to do each quote separately?
So instead of the above, I'd have to do:
string day1_c_1 = "You, along with your ";
string day1_c_2 = " friends, set up camp outside of town. You carried ";
string day1_c_3 = " units of food with you, along with another ";
string day1_c_4 = " units of metal.";
And then print it out like this:
cout << day1_c_1 << rs_q_c << day1_c_2 << rs_q_f << day1_c_3 << rs_q_m << day1_c_4

EDIT:
Variables:
int rs_q_f = 0; //Food
int rs_q_m = 0; //Metal
int rs_q_c = 0; //Companions

Edited by Youbar, 01 December 2012 - 04:15 AM.


#4 J. Evola's Apprentice   Members   -  Reputation: 307

Like
0Likes
Like

Posted 01 December 2012 - 05:11 AM

.

Edited by J. Evola's Apprentice, 01 December 2012 - 05:15 AM.


#5 Zaoshi Kaba   Crossbones+   -  Reputation: 4095

Like
1Likes
Like

Posted 01 December 2012 - 05:13 AM

Which compiler are you using?
If it's newest GCC or Visual Studio 2012 you should have to_string function:
string text = day1_c_1 + to_string(rs_q_c) + day1_c_2 + to_string(...) + ...;


#6 ifthen   Members   -  Reputation: 820

Like
3Likes
Like

Posted 01 December 2012 - 05:17 AM

There is a C++ type for doing exactly this. Its name is std::stringstream. Usage example:
[source lang="cpp"]#include <sstream>//declare it somewherestd::stringstream ss; //internal string empty at beginning//usagess << "You, along with your " << numFriends << " friends, set up camp..."; //append this to the internal stringstd::string setUpCampLabel = ss.str(); //get a copy of stringbuilder internal stringss.clear(); //clear the internal stringss << "You were eaten by a bear!";std::cout << setUpCampLabel << std::endl <<ss.str(); //it is possible to print the internal string directly[/source]

#7 Youbar   Members   -  Reputation: 122

Like
0Likes
Like

Posted 01 December 2012 - 05:28 AM

#include <sstream>
//declare it somewhere
std::stringstream ss; //internal string empty at beginning
//usage
ss << "You, along with your " << numFriends << " friends, set up camp..."; //append this to the internal string
std::string setUpCampLabel = ss.str(); //get a copy of stringbuilder internal string
ss.clear(); //clear the internal string
ss << "You were eaten by a bear!";
std::cout << setUpCampLabel << std::endl <<ss.str(); //it is possible to print the internal string directly
How is this any more efficient than just putting:
cout << "You, along with your " << numFriends << " friends, set up camp..." << endl << "You were eaten by a bear!"
I'm also using DevC++, not Visual Studio.
So, in short, you simply can't declare a string and put an integer variable within it? You have to do that?

#8 Zaoshi Kaba   Crossbones+   -  Reputation: 4095

Like
1Likes
Like

Posted 01 December 2012 - 07:54 AM

  • You should Google "Why you shouldn't use Dev-C++".
  • More lines != less efficient
  • String and integer are very different, so you have to convert it somehow, stringstream is one of ways. Even if other languages allow to simply put variable name in the string, internally it still does something similar to this.

You can create function that'll convert it:
template<typename T>
string to_string(T v) {
	stringstream str;
	str << v;
	return str.str();
}

Edited by Zaoshi Kaba, 01 December 2012 - 07:57 AM.


#9 superman3275   Crossbones+   -  Reputation: 2011

Like
0Likes
Like

Posted 01 December 2012 - 10:56 AM

Sorry! I got std::to_int() mixed up with std::to_string! Please forgive me :)!

For all intensive purposes, std::to_int doesn't exist and please disregard my old comment.

Edited by superman3275, 01 December 2012 - 12:29 PM.

I'm a game programmer and computer science ninja ph34r.png!

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

 

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here smile.png!


#10 SiCrane   Moderators   -  Reputation: 9541

Like
0Likes
Like

Posted 01 December 2012 - 11:09 AM

There's no such thing as std::to_int(). The closest thing in behavior would be std::stoi(), the closest thing in name would be the to_int_type() member function of the char traits classes.

#11 Cornstalks   Crossbones+   -  Reputation: 6974

Like
1Likes
Like

Posted 01 December 2012 - 11:13 AM

#include <sstream>
//declare it somewhere
std::stringstream ss; //internal string empty at beginning
//usage
ss << "You, along with your " << numFriends << " friends, set up camp..."; //append this to the internal string
std::string setUpCampLabel = ss.str(); //get a copy of stringbuilder internal string
ss.clear(); //clear the internal string
ss << "You were eaten by a bear!";
std::cout << setUpCampLabel << std::endl <<ss.str(); //it is possible to print the internal string directly
How is this any more efficient than just putting:
cout << "You, along with your " << numFriends << " friends, set up camp..." << endl << "You were eaten by a bear!"

First, efficiency wasn't your question. How to put variables into a string was, and that's what was shown. Yes, doing that is "less efficient" than just printing everything out to cout directly.

I'm also using DevC++, not Visual Studio.

Why you shouldn’t use Dev-C++ (or maybe you're using an updated version of Dev-C++?)

So, in short, you simply can't declare a string and put an integer variable within it? You have to do that?

Nope. Welcome to C++ :). You either have to use stringstream, to_string() (as Zaoshi Kaba showed), itoa() (please, please, please don't use this), your own custom method, an external library like boost and its lexical_cast, etc.

@superman3275: Did I miss something? I thought he was trying to put ints into strings, not strings into ints...
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#12 Servant of the Lord   Crossbones+   -  Reputation: 18491

Like
0Likes
Like

Posted 01 December 2012 - 11:31 AM

There are two good methods of converting variables into a string, both already mentioned. They are the 'correct' answer, as far as any answer could be correct.

Method one: Use streams for complex formatting.
std::stringstream myStream;
myStream << "Meow " << number << " wuff " << myFloat << " blah blah " << otherStuff;
std::string myResult = myStream.str();

Method two: Use a standalone function for simple formatting.
std::string myResult = "blah = " << IntToString(blah);

'IntToString()' is not a pre-existing function (though there are C-style functions that do similar in the standard library, they don't give out a std::string).

You can make your own like this: (this code has to go in a header file)
#include <sstream>

template<typename Type>
std::string ConvertToString(Type value)
{
    std::stringstream sstream;
    sstream << value;
   
    return sstream.str();
}

template<typename Type>
Type ConvertFromString(const std::string &str)
{
    std::stringstream sstream;
    sstream << str;
   
    Type type;
    sstream >> type;
   
    return type;
}

And you can use it like this:
std::string myStr = ConvertToString(myInt);
int myInt = ConvertFromString<int>(myStr);

Well, if you use:

int ParsedNumber = std::to_int(StringThatNeedsParsing);

Like SiCrane, I'm confused by this statement. Where is "std::to_int" found in the standard library? It wasn't in the old standard, and with a few quick googles I can't find it in C++11 either. Is it a non-standard extension for some compiler?
It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#13 Chad Smith   Members   -  Reputation: 1100

Like
0Likes
Like

Posted 01 December 2012 - 11:56 AM

Like SiCrane, I'm confused by this statement. Where is "std::to_int" found in the standard library? It wasn't in the old standard, and with a few quick googles I can't find it in C++11 either. Is it a non-standard extension for some compiler?


Can't find it either anywhere or even a single mention of something really like this anywhere on Google. Something tells me he was mistaken, somehow got different languages mixed up, or something else.

#14 Álvaro   Crossbones+   -  Reputation: 12911

Like
0Likes
Like

Posted 01 December 2012 - 12:12 PM

One could still do what we used to do in C, and then put the result in a string:
char buffer[100];
std::snprintf(buffer, 100, "Hi, I am %d years old.", x);
std::string my_string(buffer);
That's kind of ugly, because it requires you to come up with an upper bound for the space needed for the string, and because it formats the string in one buffer and then you need to copy it if you want it as a string. But if you need to do any formatting of the numbers, it's much easier to use the printf family of functions than <iomanip>. You can also pick different formatting strings dynamically, which is much more flexible than the other methods.

Another interesting alternative for formatting is Boost Format..

Edited by Álvaro, 01 December 2012 - 12:12 PM.


#15 superman3275   Crossbones+   -  Reputation: 2011

Like
1Likes
Like

Posted 01 December 2012 - 12:28 PM

I'm sorry, I mixed up that funtion. What I meant was std::to_string. When I had a score counter in Pong, I had an integer that I used to keep track of the score. To display the score, I had to convert the integer to a string, so I used std::to_string. I must have mixed that up with a function to convert strings to ints, so I'm sorry. Either way, I would use std::stringstream for this. Very Sorry :)!

Edited by superman3275, 01 December 2012 - 12:30 PM.

I'm a game programmer and computer science ninja ph34r.png!

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

 

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here smile.png!


#16 superman3275   Crossbones+   -  Reputation: 2011

Like
0Likes
Like

Posted 01 December 2012 - 12:30 PM

Also, I'm not sure if DevC++ even supports std::stringstream?

I'm a game programmer and computer science ninja ph34r.png!

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

 

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here smile.png!


#17 Servant of the Lord   Crossbones+   -  Reputation: 18491

Like
0Likes
Like

Posted 01 December 2012 - 01:43 PM

I'm sorry, I mixed up that funtion. What I meant was std::to_string.

Excellent, so that's a new C++11 function? Good to know; thanks for posting that!

Also, I'm not sure if DevC++ even supports std::stringstream?

Dev C++ is an IDE, it uses MinGW as the compiler, and MinGW's C++ library implements the standard. Though the version of MinGW that ships with Dev C++ is probably outdated.

Still, I recommend QtCreator over Dev C++.

Edited by Servant of the Lord, 01 December 2012 - 01:44 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#18 Youbar   Members   -  Reputation: 122

Like
0Likes
Like

Posted 01 December 2012 - 03:38 PM

Gosh, never realised this. Could I perhaps use Notepad++ over all the other options? I tried to find if Visual Studio was free, but all I got was trials. If someone could perhaps give me a link to the free version (not for Windows 8), it'd be appreciated. How do I register for a free product key?
Nevermind.

Edited by Youbar, 01 December 2012 - 03:47 PM.


#19 Youbar   Members   -  Reputation: 122

Like
0Likes
Like

Posted 01 December 2012 - 04:43 PM

I have another problem, now.

int wait(int x)
{
Sleep(1000) * x;
}

returns:
error C2296: '*' : illegal, left operand has type 'void'

#20 SiCrane   Moderators   -  Reputation: 9541

Like
0Likes
Like

Posted 01 December 2012 - 04:46 PM

Did you mean Sleep(1000 * x)?




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS