2

I want to append integer value with string value but not a variable.

I tried to put an integer value which is variable with a string called February. I tried it using += operator but it did not work.

string getMonth(day) { if(day >=31 ){ day -= 31; "February "+=day; } } 
3
  • 3
    Possible duplicate of How do you append an int to a string in C++? Commented Jul 22, 2019 at 10:13
  • @NO_NAME it you see a dupe, just vote to close with respective reason (comment you have used will be auto added). Commented Jul 22, 2019 at 10:16
  • 2
    @MarekR I did just that? Well, I cannot vote to close because I don't have 3,000 reputation but I've clicked option flag and it auto-added the comment. Commented Jul 22, 2019 at 10:21

2 Answers 2

5

Do something like

#include <string> // ... std::string s( "February " ); s += std::to_string( day ); 

Here is a demonstrative program

#include <iostream> #include <string> int main() { std::string s( "February " ); int day = 20; s += std::to_string( day ); std::cout << s << '\n'; } 

Its output is

February 20 

Another approach is to use a string stream.

Here is one more demonstrative program.

#include <iostream> #include <sstream> #include <string> int main() { std::ostringstream oss; int day = 20; oss << "February " << day; std::string s = oss.str(); std::cout << s << '\n'; } 

Its output is the same as shown above.

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

10 Comments

I included string still it shows : "to_string was not defined" error is shown."
@BiploveLamichhane If you copied the call exactly as it is written that is you used the qualified name std::to_string then maybe you need a more modern C++ compiler.
std::to_string is part of the standard since c++11. What compiler do you use?
@NO_NAME I am using dev c++ version 5.11
OK, Dev-C++ is an environment, not a compiler but close enough. Wiki says that it uses MinGW (basically GCC) in version that should support c++11. Maybe is is not default in this version? Try to manually add -std=c++11 to compiler options.
|
0

The answer above solved my problem.. If you are using dev c++ like me then you might be in the same problem, I would recommend you to add -std=c++11. For this you can got to this link How to change mode from c++98 mode in Dev-C++ to a mode that supports C++0x (range based for)? and go to second answer. Thank you

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.