• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Youbar

Variables within strings? (C++)

23 posts in this topic

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
0

Share this post


Link to post
Share on other sites
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 :
[code]
std::string s = "hi" + yourstring;
[/code]

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 :(
0

Share this post


Link to post
Share on other sites
[CODE]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.";[/CODE]

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:
[CODE]
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.";
[/CODE]
And then print it out like this:
[CODE]
cout << day1_c_1 << rs_q_c << day1_c_2 << rs_q_f << day1_c_3 << rs_q_m << day1_c_4[/CODE]

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

Share this post


Link to post
Share on other sites
Which compiler are you using?
If it's newest GCC or Visual Studio 2012 you should have to_string function:
[CODE]
string text = day1_c_1 + to_string(rs_q_c) + day1_c_2 + to_string(...) + ...;
[/CODE]
1

Share this post


Link to post
Share on other sites
[CODE]#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[/CODE]
How is this any more efficient than just putting:
[CODE]cout << "You, along with your " << numFriends << " friends, set up camp..." << endl << "You were eaten by a bear!"[/CODE]
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?
0

Share this post


Link to post
Share on other sites
[list=1]
[*]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.
[/list]

You can create function that'll convert it:
[code]
template<typename T>
string to_string(T v) {
stringstream str;
str << v;
return str.str();
}
[/code] Edited by Zaoshi Kaba
1

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
[quote name='Youbar' timestamp='1354361330' post='5006012']
[CODE]#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[/CODE]
How is this any more efficient than just putting:
[CODE]cout << "You, along with your " << numFriends << " friends, set up camp..." << endl << "You were eaten by a bear!"[/CODE]
[/quote]
First, efficiency wasn't your question. How to put variables into a [font=courier new,courier,monospace]string[/font] was, and that's what was shown. Yes, doing that is "less efficient" than just printing everything out to [font=courier new,courier,monospace]cout[/font] directly.

[quote name='Youbar' timestamp='1354361330' post='5006012']
I'm also using DevC++, not Visual Studio.
[/quote]
[url="http://clicktobegin.net/programming/why-you-shouldnt-use-dev-c/"]Why you shouldn’t use Dev-C++[/url] ([url="http://clicktobegin.net/programming/updated-versions-of-dev-c/"]or maybe you're using an updated version of Dev-C++?[/url])

[quote name='Youbar' timestamp='1354361330' post='5006012']
So, in short, you simply can't declare a string and put an integer variable within it? You have to do that?
[/quote]
Nope. Welcome to C++ :). You either have to use [font=courier new,courier,monospace]stringstream[/font], [font=courier new,courier,monospace]to_string()[/font] (as Zaoshi Kaba showed), [font=courier new,courier,monospace]itoa()[/font] (please, please, please don't use this), your own custom method, an external library like [font=courier new,courier,monospace]boost[/font] and its [font=courier new,courier,monospace]lexical_cast[/font], etc.

@superman3275: Did I miss something? I thought he was trying to put [font=courier new,courier,monospace]int[/font]s into [font=courier new,courier,monospace]string[/font]s, not [font=courier new,courier,monospace]string[/font]s into [font=courier new,courier,monospace]int[/font]s...
1

Share this post


Link to post
Share on other sites
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.
[code]std::stringstream myStream;
myStream << "Meow " << number << " wuff " << myFloat << " blah blah " << otherStuff;
std::string myResult = myStream.str();[/code]

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

'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)
[code]#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;
}[/code]

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

[quote name='superman3275' timestamp='1354380973' post='5006040']
Well, if you use:

[CODE]
int ParsedNumber = std::to_int(StringThatNeedsParsing);
[/CODE]
[/quote]
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?
0

Share this post


Link to post
Share on other sites
[quote name='Servant of the Lord' timestamp='1354383096' post='5006050']

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?
[/quote]

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

Share this post


Link to post
Share on other sites
One could still do what we used to do in C, and then put the result in a string:
[code]char buffer[100];
std::snprintf(buffer, 100, "Hi, I am %d years old.", x);
std::string my_string(buffer);[/code]
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 [url="http://www.boost.org/doc/libs/1_52_0/libs/format/doc/format.html"]Boost Format.[/url]. Edited by Álvaro
0

Share this post


Link to post
Share on other sites
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
1

Share this post


Link to post
Share on other sites
[quote name='superman3275' timestamp='1354386523' post='5006063']
I'm sorry, I mixed up that funtion. What I meant was std::to_string.[/quote]
Excellent, so that's [url="http://en.cppreference.com/w/cpp/string/basic_string/to_string"]a new C++11 function[/url]? Good to know; thanks for posting that!

[quote name='superman3275' timestamp='1354386619' post='5006064']
Also, I'm not sure if DevC++ even supports std::stringstream?
[/quote]
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 [url="http://qt-project.org/wiki/Category:Tools::QtCreator"]QtCreator[/url] over Dev C++. Edited by Servant of the Lord
0

Share this post


Link to post
Share on other sites
[s]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?[/s]
Nevermind. Edited by Youbar
0

Share this post


Link to post
Share on other sites
I have another problem, now.

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

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

Share this post


Link to post
Share on other sites
Ah, thanks. That solved the problem.
But now it's saying I have to return a value...
error C4716: 'wait' : must return a value
0

Share this post


Link to post
Share on other sites
It's telling you the problem. You declared your function to return an int, so the compiler is telling you that you aren't doing that. If you don't want the function to return a value then change the function to return void.
1

Share this post


Link to post
Share on other sites
[CODE]int wait(int x)
{
Sleep(1000 * x);
return (x);
}[/CODE]

Code fixed by doing this, just in case someone happens to be reading this in the future.
0

Share this post


Link to post
Share on other sites
SiCrane described your problem. The correct version is
[source lang="cpp"]void wait(int x)
{
Sleep(1000 * x);
}[/source]
By writing "int" in front of your function, you are saying that it will return an integer. But why should you return an integer in a wait function? If you write "void" instead, you are saying that the function does not return anything.
Solve your problems by thinking about them, not by strafing around them. Edited by ifthen
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0