I was wondering how I could convert an int to a string and then add it to an existin string. i.e.
std::string s = "Hello";
//convert 1 to string here
//add the string 1 to s
I hope I'm making sense. Thank you very much in advance for any answer.
If the number you want to append is an integer or floating point variable, then use std::to_string and simply "add" it:
int some_number = 123;
std::string some_string = "foo";
some_string += std::to_string(some_number);
std::cout << some_string << '\n';
Should output
foo123
The "modern" way is to use std::to_string(1). In fact, various overloads of std::to_string exist for different number types.
Putting this together you can write std::string s = "Hello" + std::to_string(1);
Alternatively you can use std::stringstream which can be faster due to fewer string concatenation operations which can be expensive:
std::stringstream s;
s << "Hello" << 1;
// s.str() extracts the string
Related
I have a string with 6 Integer numbers inside of it '''string myStr = "1 2 3 4 5 6"'''
I want to use a stringstream to read all of those numbers individually and add them all up to find the sum.
This is part of a homework problem, just to clarify, and I need to use stringstreams as a way to read the string and add up all the numbers inside.
Here is the prompt:
"Create a string with a series of six numbers. With the help of a stringstream, add all numbers in the string"
Note:
Sorry if this is a badly structured question. any criticism of how I could make this more clear is appreciated.
I have searched for a way to do this but I am having trouble understanding just exactly how this works.
I know you need to use '''ostringstream''' or '''istringstream''' to do whatever it is I am trying to do. But I do not know HOW to use them.
I do have a coursebook "Murach's C++ Programming" which is the book we have for reference in class. But it does not go over anything about stringstreams in any other context besides reading from text files.
void stringstreams(string myStr = "1 2 3 4 5 6"){
stringstream strStream;
strStream << myStr;
myStr = strStream.str();
cout << myStr << endl;
}
Describe results:
I think all this does is send the string into a stringstream, and then send it right back the other way (I may be completely wrong about that). I am not exactly sure what to do because I don't have ANY experience whatsoever working with stringstream.
Here is another way to use the std::stringstream, without having to manually convert the string to an integer:
#include <sstream>
#include <string>
#include <iostream>
int main()
{
std::string myStr = "1 2 3 4 5 6";
std::stringstream strm(myStr);
int value;
int sum = 0;
while (strm >> value)
sum += value;
std::cout << sum << "\n";
}
See if this simple commented code helps:
int main() {
std::string myStr = "1 2 3 4 5 6";
std::stringstream ss{ myStr}; // Initialize the stringstream; use stringstream instead if you are confused with ostringstream vs istringstream
string str;
int sum = 0;
while (getline(ss, str, ' ')) { // split stringstream into tokens separated by a whitespace
sum += std::atoi(str.c_str()); // convert each string to c- equivalent before converting to integer using atoi
}
std::cout << sum << endl;
}
So basically I'm trying to add a character in the middle of a string. Normally in something like Python, this would be pretty straightforward, but I'm really not sure how to achieve this in C++. What I'm trying to achieve is something like this:
void converter(){
converted = ":regional_indicator_" + character + ":";
}
So basically, I'm trying to add the variable character of a type char in a string. Should I be storing character as a string instead?
For reference here's all of my code:
#include <iostream>
using namespace std;
string inputLine;
char character;
string converted;
void input(){
cout << "Please input the text in which you would like to be converted" << endl;
cin >> inputLine;
}
void converter(){
converted = ":regional_indicator_" + character + ":";
}
int main(){
input();
for (int i = 0; i < inputLine.length(); i++ ){
character = tolower(inputLine[i]);
}
return 0;
}
Append s behind the strings literals to treat them as std::strings instead of const char*s:
converted = ":regional_indicator_"s + character + ":"s;
You would need to do either using namespace std::literals or using namespace std::string_literals for it to work.
On a side note, in C++, it is strange to have a function converter() to modify a global variable using another global variable. You might want to consider passing character as a parameter to the function instead.
You can do it like this:
converted = ":regional_indicator_" + std::string(1, character) + ":";
This works because adding a string literal (const char *) to a string yields a string. But adding const char * and char results in pointer arithmetic. So, by constructing a std::string from "character" you end up with const char * + std::string yielding a string and then std::string + const char * again yields a string as the final result.
You can avoid invoking the std::string() constructor and memory allocation by using following. I have tested this before posting and it works:
void converter(){
converted = ":regional_indicator_";
converted.push_back(character);
converted.push_back(':');
}
It's better because "converted" already will have some extra memory reserved, so you will just be filling that extra memory with two more characters and won't be allocating new memory.
The wasy way to build strings is to use a std::ostringstream like this:
void converter(){
std::ostringstream oss;
oss << ":regional_indicator_" << character << ":";
converted = oss.str(); // copy the string out
// ... etc ...
}
The added advantage of that method is it converts numbers to string automatically too.
That's not the fastest way so if speed was important I would take advantage of the static nature of this concatenation like this:
std::string converter(){
static char* template = ":regional_indicator_X:";
template[20] = character; // replace the `X` with your character
converted.assign(template, 21); // assign your string all at once
// ... etc ...
}
That works because your string is of fixed length. If thread safety is required you can use thread_local static char* template....
Hello? I want to know "how to convert char to string"
This is my C code
string firSen;
int comma1=0;
cout<<"Please write your sentence"<<endl;
getline(cin,first);
int a=firSen.first("string");
for(i=a;firSen[i] != ',';i++)
comma1=i;
cout<<firSen[comma1-3]<<firSen[comma1-2]<<firSen[comma1-1]<<endl;
I will write "The string is 100s, Thank you"
I know firSen[comma1-3]=1, firSen[comma1-2]=0, firSen[comma1-1]=0 for type of char.
And I want to put these char into string
(Like 1,0,0 into string of 100) because I want to use atoi function....
Do you know how to convert char into string?
You can use std::istringstream instead of atoi.
Something like this:
std::istringstream ss(firSen.substr(comma1-3));
int val;
ss >> val;
In this case, if you know the location and length that you want, you can just extract a substring:
std::string number(firSen, comma1-3, 3);
and convert that to an integer type using the C++11 conversion functions:
int n = std::stoi(number);
or, historically, a string stream:
int n;
std::stringstream ss(number);
ss >> n;
or, if you want to be really old-school, the C library
int n = std::atoi(number.c_str());
There are other ways of building strings. You can initialise it from a list of characters:
std::string number {char1, char2, char3};
You can append characters and other strings:
std::string hello = "Hello";
hello += ',';
hello += ' ';
hello += "world!";
or use a string stream, which can also format numbers and other types:
std::stringstream sentence;
sentence << "The string is " << 100 << ", thank you.";
so I have a string that has a hex value in it. For example, my string may have
string a = "0x4D";
Would it be possible to assign 0x4D to a char? Because I know that if I had
char c = 0x4D
then I could print out its ASCII symbol, which would be M.
Is it possible to store "0x4D" into a char so that I can print out its ascii symbol? If anyone has any tips, that would be appreciated! If there's a better way to do this, please let me know! Thanks!
You can use strtol to convert the string to a number. You can then print this number or do other things you like with it.
Oh wait, you tagged it C++, and strtol is very much C-style. In C++, you can use a stringstream, and extract a number from it.
You can use std::stoi to convert the string to an integer (the base is auto-detected from the 0x prefix):
std::string str = "0x4D";
char c = static_cast<char>(std::stoi(str));
std::cout << c << std::endl;
However, this is not guaranteed to give you the ASCII character for that value. There are various translations between character sets that occur in this simple code alone. For example, the chars in the string literal "0x4D" are initialized with the corresponding value in the implementation-defined execution character set. The printed character is also up to interpretation by the medium that is displaying it.
The best you could do is provide a mapping from ASCII values to characters. You could do this with an array where the index is the ASCII value and the element is the corresponding character.
To use stringstreams as Bas suggests:
int x;
string s = "0x10";
stringstream ss;
ss << hex << s;
ss >> x;
But I think it's a wasteful way to do it.
Here is a solution based on std::stringstream:
std::istringstream iss ("0x4D");
iss.flags(std::ios::hex);
int i;
iss >> i;
std::cout << "[" << (char)i << "]" << std::endl; //--> prints "[M]"
everybody I have problem with string concatenation in C++, here is my code
map<double, string> fracs;
for(int d=1; d<=N; d++)
for(int n=0; n<=d; n++)
if(gcd(n, d)==1){
string s = n+"/"+d;// this does not work in C++ but works in Java
fracs.insert(make_pair((double)(n/d), s));
}
How can I fix my code?
Try like this.
stringstream os;
os << n << "/" << d;
string s =os.str();
In C++ you have to convert an int to a string before you can concatenate it with another string using the + operator.
See Easiest way to convert int to string in C++.
Use streams, in your case, a stringstream:
#include <sstream>
...
std::stringstream ss;
ss << n << '/' << d;
Later, when done with your work, you can store it as an ordinary string:
const std::string s = ss.str();
Important (side-) note: Never do
const char *s = ss.str().c_str();
stringstream::str() produces a temporary std::string, and according to the standard, temporaries live until the end of the expression. Then, std::string::c_str() gives you a pointer to a null-terminated string, but according to The Holy Law, that C-style-string becomes invalid once the std::string (from which you receved it) changes.
It might work this time, and next time, and even on QA, but explodes right in the face of your most valuable customer.
The std::string must survive until the battle is over:
const std::string s = ss.str(); // must exist as long as sz is being used
const char *sz = s.c_str();
n and d are integers. Here is how you can convert integer to string:
std::string s;
std::stringstream out;
out << n << "/" << d;
s = out.str();
You could use a stringstream.
stringstream s;
s << n << "/" << d;
fracs.insert(make_pair((double)n/d, s.str()));
No one has suggested it yet but you can also take a look at boost::lexical_cast<>.
While this method is sometimes criticized because of performance issues, it might be ok in your situation, and it surely makes the code more readable.
Unlike in Java, in C++ there is no operator+ that explicitly converts a number to a string. What is usually done in C++ in cases like this is...
#include <sstream>
stringstream ss;
ss << n << '/' << d; // Just like you'd do with cout
string s = ss.str(); // Convert the stringstream to a string
I think sprintf(), which is a function used to send formatted data to strings, would be a much clearer way to do it. Just the way you would use printf, but with the c-style string type char* as a first(additional) argument:
char* temp;
sprint(temp, "%d/%d", n, d);
std::string g(temp);
You could check it out at http://www.cplusplus.com/reference/cstdio/sprintf/