How to concatenate a char* and a string? - c++

My problem is that I get an error when trying to add hard-coded text, "334 " before my decoded user input:
received = buf;
if(strncmp(buf, "334 ", 4) == 0){
decoding(received.c_str() + 4, strlen(buf + 4), buf);
received = "334 " + buf;
}
Here is the error I get:
invalid operands of types 'const char[5] and 'char[300] to binary 'operator+'

std::string has a constructor that takes a char *, so you can create a std::string from buf like this:
std::string buf_str(buf);
From cplusplus.com's list of std::string constructors:
string (const char* s);
Copies the null-terminated character sequence (C-string) pointed by s.

I dunno if that can suit you but you can consider using the stringstream class so that you can merge the text variables as:
stringstream longone;
string text;
longone << received << "334 ";
string=longone.str()

Related

How to append a char type variable to a string?

I want to append a char-variable containing the password to a string saying "Your password is: ". When I use the append function for this I get an error saying I can't use this function with string. (I can only use it with unsigned int and char.)
char pass[64];
std::cout << "Enter a password: "; fgets(pass, 64, stdin);
std::string ssifre = "Your password is: "; ssifre.append(sizeof(pass), pass);
If you know another way to solve this, please comment. I don't need to use this function.
This should work:
ssifre += pass;
It's using the += operator
(note that as #MichaelDoubez mentionned in the comments, ssifre.append(pass) would work, too.)
ssifre.append(sizeof(pass), pass) is trying to call the append(size_type count, CharT ch) overloaded version, which appends ch count times. That does not work since pass[] is not a single char, it is an array of chars.
You need to use the append(const CharT* s) overloaded version instead (especially since fgets() ensures that pass[] will be null-terminated, and append(const CharT* s) expects a null-terminated char* string). A fixed char[] array decays into a char* pointer to the 1st char element:
ssifre.append(pass);
That being said, you really shouldn't be using a char[] array in this situation to begin with. You should be reading in a std::string instead:
std::string pass;
std::cout << "Enter a password: ";
std::getline(std::cin, pass);
std::string ssifre = "Your password is: " + pass;

How to create new string in C++ by two other ones? [duplicate]

This question already has answers here:
Concatenating strings doesn't work as expected [closed]
(4 answers)
Closed 6 years ago.
I want to create string "hello1world by this two strings:
string s1 = "hello"
string s2 = "world"
I do this:
string my_str;
sprintf(my_str, "%s1%s", s1, s2);
But I have an error:
error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘char*’ for argument ‘1’ to ‘int sprintf(char*, const char*, ...)’
sprintf(my_str, "%s1%s", s1, s2);
How to do it properly?
Please don't use sprintf. It only supports char[] strings, i.e. C strings. So that's why it doesn't compile when you pass std::string.
With std::string, a simple + is all you need:
string my_str = s1 + s2;
If you want to concatenate the two strings, you can use + operator of std::string
string s1 = "hello";
string s2 = "world";
string my_str = s1 + "1" + s2;
For case of two strings formatting use operator+=:
std::string myStr(s1 + "1" + s2);
If you need to do formatting of many strings, a more efficient way will be:
std::string myStr;
myStr.reserve(1048576); // Reserve space in buffer to prevent reallocation
while (<many iterations>)
{
myStr.append(s1);
myStr.append("1");
// Do more formatting here
myStr.append(s2);
}
If you have some non-string values to include in your result you can use std::stringstream from <sstream> header:
std::stringstream ss;
ss << "hello";
ss << 1;
ss << "world";
std::string myStr(ss.str());
I need to mention (thanks #IInspectable for hint) std::stringstream is pretty slow. C++11 offers better way for numbers formatting with use of std::to_string.
std::string s3 = s1 + "1" + s2;
you have many things to do you can use operator +
string a = "hello";
string b = "world";
string ans = a + "1" + b;
you can use string::append
string a = "hello";
string b = "world";
string ans = "";
ans.append(a);
ans.append("1");
ans.append(b);
you can use insert but not pereferd in concate better use + operator or append
string a = "hello";
string b = "world";
a.insert(a.size(),1,'1');
a.insert(a.size(),b);
insert with a string use it as string::insert(index,string);
with characters use it as string::insert(index,len,char);

How do I concatenate "constant strings" and chars?

What is the "proper way" to do the following? (Note, I don't want to output the message to the screen (yet), the data needs to be stored in a variable.)
std::cout << "Enter a letter: ";
char input;
std::cin >> input;
std::string message = "Today's program was brought to you by the letter '" + input + "'.";
The code gives me the error message invalid operands of types const char* and const char [3] to binary operator+.
I understand why this message is occurring. When Googling for a solution, the results that come up recommend casting each item into a string in turn. However, this becomes impractical if you have to concatenate a dozen items:
std::string("x:") + x + std::string(", y:") + y + std::string(", width:") + width + std::string(", height:") + height + ...;
What is the "proper way" in c++ to concatenate strings, chars, char arrays, and any other data that is convertible, into a single string? Is there anything like Python's beautiful string formatting features in c++?
What you are trying to do won't work because C++ views your concatenation as an attempt to add several char pointers. If you explicitly cast the first element in the series to an std::string it should work.
Change your original code
string message = "Today's program was brought to you by the letter '" + input + "'.";
to this:
string message = std::string("Today's program was brought to you by the letter '")
+ input + "'.";
q.v. this SO post which discusses this problem in greater detail (though I don't know why it got closed as not being a real question).
There's several ways to do this, but one way that's a good balance between simplicity of implementation and convenience is to use a "formatter" class which wraps std::stringstream like so:
string message = formatter() << "Today's program was brought to you by the letter '" << input << "'.";
Where formatter can be defined very simply in a header file as follows:
#include <sstream>
class formatter {
public:
template <typename T>
formatter & operator<<(const T & o) {
stream_ << o;
return *this;
}
const std::string str() const { return stream_.str(); }
operator std::string() {
return stream_.str();
}
private:
std::ostringstream stream_;
};
What's going on there: If you try to use a temporary std::stringstream() instead of formatter() above, it doesn't work because
std::stringstream is not implicitly convertible to std::string
You can't even do it like this
std::string message = (std::stringstream() << "foo" << input << "bar").str(); because, std::stringstream returns std::ostream & from its stream operations (rather than std::stringstream &), and you cannot convert an ostream to a string in general.
The formatter class just lets you construct and use a stringstream all in one line with a minimum of boiler plate.

convert char to string

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.";

Append an int to a std::string [duplicate]

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
Closed 8 years ago.
Why is this code gives an Debug Assertion Fail?
std::string query;
int ClientID = 666;
query = "select logged from login where id = ";
query.append((char *)ClientID);
The std::string::append() method expects its argument to be a NULL terminated string (char*).
There are several approaches for producing a string containg an int:
std::ostringstream
#include <sstream>
std::ostringstream s;
s << "select logged from login where id = " << ClientID;
std::string query(s.str());
std::to_string (C++11)
std::string query("select logged from login where id = " +
std::to_string(ClientID));
boost::lexical_cast
#include <boost/lexical_cast.hpp>
std::string query("select logged from login where id = " +
boost::lexical_cast<std::string>(ClientID));
You cannot cast an int to a char* to get a string. Try this:
std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();
stringstream reference
I have a feeling that your ClientID is not of a string type (zero-terminated char* or std::string) but some integral type (e.g. int) so you need to convert number to the string first:
std::stringstream ss;
ss << ClientID;
query.append(ss.str());
But you can use operator+ as well (instead of append):
query += ss.str();
You are casting ClientID to char* causing the function to assume its a null terinated char array, which it is not.
from cplusplus.com :
string& append ( const char * s ); Appends a copy of the string formed
by the null-terminated character sequence (C string) pointed by s. The
length of this character sequence is determined by the first ocurrence
of a null character (as determined by traits.length(s)).