How to add multiple items to string in c++? - c++

I know how to do it with cout:
cout << "string" << 'c' << 33;
But how to perform this so output is redirected to variable instead directly to standard out ?
const char* string << "string" << 'c' << 33; //doesn't work

Use std::stringstream from C++ standard library.
It works like the following:
std::stringstream ss;
ss << "string" << 'c' << 33;
std::string str = ss.str();
const char* str_ansi_c = str.c_str();
Keep in mind str still needs to be in the scope while you are using C-style str_ansi_c.

#include <sstream>
#include <iostream>
main()
{
std::stringstream ss;
ss << "string" << 'c' << 33;
std::string str = ss.str();
std::cout << str;
}

Related

C++ << no operator found

string toString() {
std::stringstream punkte;
std::stringstream name;
std::cout << name << "hat" << punkte << "Punkte" << '\n'
return 0;
}
At this line of code. I'm receiving the error C++ << no operator found
I can't figure out what my mistake is. I have read and tried different solutions. But nothing works. Can somebody please help?
std::cout << name << "hat" << punkte << "Punkte" << '\n';
I also included this in my code:
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream, std::stringbuf
#include <fstream>
There is no overload of operator<<() that will format a std::stringstream to a std::ostream. There error does not lie.
You are trying to call operator "<<" with a stringstream parameter. In other words:
std::cout << name;
Is equivalent to:
std::cout.operator<<(name);
And that operator<<(const std::stringstream&) function doesn't exists.
I think that what you want to do is assign each stringstream their values and then print both, isn't?
string toString()
{
std::stringstream punkte;
std::stringstream name;
name << "hat";
punkte << "Punkte";
std::cout << name.str() << punkte.str() << std::endl;
return name.str();
}
Be careful with your return value, and remember that a std::stringstream is not a std::string. If you want to retrieve the std:string in the stream, you must call the str() method.

How can I obtain the length of a const stringstream's buffer without copying or seeking?

I have a const std::stringstream and a desire to find out how many bytes there are in its underlying string buffer.
I cannot seekg to the end, tellg then seekg to the start again, because none of these operations are available constly.
I do not want to get the str().size() because str() returns a copy and this may not be a trivial amount of data.
Do I have any good options?
(The stream itself is presented to me as const, only because it is a member of another type, and I receive a const reference to an object of that type. The stream represents the contents of a "document", its encapsulating object represents a CGI response and I am trying to generate an accurate Content-Length HTTP header line from within operator<<(std::ostream&, const cgi_response&).)
I've never been very comfortable with stream buffers, but this seems to work for me:
#include <iostream>
#include <sstream>
std::stringstream::pos_type size_of_stream(const std::stringstream& ss)
{
std::streambuf* buf = ss.rdbuf();
// Get the current position so we can restore it later
std::stringstream::pos_type original = buf->pubseekoff(0, ss.cur, ss.out);
// Seek to end and get the position
std::stringstream::pos_type end = buf->pubseekoff(0, ss.end, ss.out);
// Restore the position
buf->pubseekpos(original, ss.out);
return end;
}
int main()
{
std::stringstream ss;
ss << "Hello";
ss << ' ';
ss << "World";
ss << 42;
std::cout << size_of_stream(ss) << std::endl;
// Make sure the output string is still the same
ss << "\nnew line";
std::cout << ss.str() << std::endl;
std::string str;
ss >> str;
std::cout << str << std::endl;
}
The key is that rdbuf() is const but returns a non-const buffer, which can then be used to seek.
If you want to know the remaining available input size:
#include <iostream>
#include <sstream>
std::size_t input_available(const std::stringstream& s)
{
std::streambuf* buf = s.rdbuf();
std::streampos pos = buf->pubseekoff(0, std::ios_base::cur, std::ios_base::in);
std::streampos end = buf->pubseekoff(0, std::ios_base::end, std::ios_base::in);
buf->pubseekpos(pos, std::ios_base::in);
return end - pos;
}
int main()
{
std::stringstream stream;
// Output
std::cout << input_available(stream) << std::endl; // 0
stream << "123 ";
std::cout << input_available(stream) << std::endl; // 4
stream << "567";
std::cout << input_available(stream) << std::endl; // 7
// Input
std::string s;
stream >> s;
std::cout << input_available(stream) << std::endl; // 4
stream >> s;
std::cout << input_available(stream) << std::endl; // 0
}
This is similar to #Cornstalks solution, but positions the input sequence correctly.
This should work :))
#include <iostream>
#include <sstream>
#include <boost/move/move.hpp>
int main()
{
const std::stringstream ss("hello");
std::cout << boost::move(ss).str().size();
}

how to print Ascii code of a string in c++

I have a string and I want to print hex value of each parts ascii code.
for example if the string is "0200" the output will be 30323030 .
and here's my code:
string bit_pattern;
bit_pattern = "5678008180000000";
cout << hex << bit_pattern;
but it prints 5678008180000000 instead of 35363738303038313830303030303030
how do i fix it???
You can use the following
for (int i=0; i<bit_pattern.length(); i++)
cout << hex << (int)bit_pattern[i];
to print the ascii value (in hex format) char by char.
You're just sending the same std::string right to std::cout. Just sending the hex manipulator isn't going to magically convert all those chars.
I admit this is complete overkill, but I was bored:
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
class ascicodes
{
std::ostringstream ss;
public:
friend std::ostream& operator <<(std::ostream& os, const ascicodes& obj)
{
os << obj.ss.str();
return os;
}
ascicodes(const std::string& s)
{
ss << std::hex << std::setfill('0');
std::for_each(s.begin(), s.end(),
[this](char ch)
{
ss << std::setw(2) << static_cast<unsigned int>(ch);
});
}
};
int main()
{
std::string bit_pattern = "5678008180000000";
std::cout << ascicodes(bit_pattern) << std::endl;
std::cout << ascicodes("A completely different string") << std::endl;
return 0;
}
Output
35363738303038313830303030303030
4120636f6d706c6574656c7920646966666572656e7420737472696e67

Convert char* array of integers to hex

I have a struct that stores the integer value as a custom string type.
typedef char OneLine[MAX_LINE + 1];
So I have some instances where I want the string that contains "12" to be converted to
C.
OneLine testString;
strcpy(testString, "12");
I'd like a way for me to convert testString to be "C"
How should I tackle this?
Thanks in advance.
You can use sscanf to convert "12" to an integer 12. Then you can use sprintf with %x format to convert integer 12 to "C"
The conversion can be done using stringstreams
#include <iostream>
#include <sstream>
#include <string>
#include <ios>
int main()
{
char const *str = "12";
std::istringstream iss( str );
int val;
if( !( iss >> val ) ) {
// handle error
}
std::ostringstream oss;
oss << std::hex << val;
std::cout << oss.str() << std::endl;
}
Or slightly less verbose way with C++11
char const *str = "12";
auto val = std::stoi( str );
std::ostringstream oss;
oss << std::hex << val;
std::cout << oss.str() << std::endl;
First, even if you were to do this manually, you shouldn't use char arrays for strings. Use std::[w]string.
Second, you can do this with std::[w][i|o]stringstream:
istringstream iss("12");
int number;
iss >> number;
ostringstream oss;
oss << hex << number;
const string& hexNumber = oss.str();
// hexNumber now contains "C"

how do i add a int to a string

i have a string and i need to add a number to it i.e a int. like:
string number1 = ("dfg");
int number2 = 123;
number1 += number2;
this is my code:
name = root_enter; // pull name from another string.
size_t sz;
sz = name.size(); //find the size of the string.
name.resize (sz + 5, account); // add the account number.
cout << name; //test the string.
this works... somewhat but i only get the "*name*88888" and... i don't know why.
i just need a way to add the value of a int to the end of a string
There are no in-built operators that do this. You can write your own function, overload an operator+ for a string and an int. If you use a custom function, try using a stringstream:
string addi2str(string const& instr, int v) {
stringstream s(instr);
s << v;
return s.str();
}
Use a stringstream.
#include <iostream>
#include <sstream>
using namespace std;
int main () {
int a = 30;
stringstream ss(stringstream::in | stringstream::out);
ss << "hello world";
ss << '\n';
ss << a;
cout << ss.str() << '\n';
return 0;
}
You can use string streams:
template<class T>
std::string to_string(const T& t) {
std::ostringstream ss;
ss << t;
return ss.str();
}
// usage:
std::string s("foo");
s.append(to_string(12345));
Alternatively you can use utilities like Boosts lexical_cast():
s.append(boost::lexical_cast<std::string>(12345));
Use a stringstream.
int x = 29;
std::stringstream ss;
ss << "My age is: " << x << std::endl;
std::string str = ss.str();
you can use lexecal_cast from boost, then C itoa and of course stringstream from STL