I tried to print the value that exists in the ostream variable by convert to string, and then to print the string instead the ostream argument.
But it's not working.
This is my code:
#include <iostream>
#include <cassert>
#include <cstring>
#include <sstream>
using std::ostream;
typedef std::basic_stringstream<char> stringstream;
class X {
public:
int y;
};
std::ostream& operator<<(std::ostream& os, const X x) {
return os << x.y;
}
int main() {
X x;
x.y = 5;
stringstream ss;
ostream output(nullptr);
output << x;
ss << output.rdbuf();
std::string myString = ss.str();
std::cout << x << std::endl; // 5
std::cout << "myString.c_str() :" << std::endl;
std::cout << myString.c_str() << std::endl; // nothing.
}
How can I fix this problem so that I will get at myString.c_str() the appropriate output?
the output in std::cout << myString.c_str() << std::endl; line is "" (empty string - nothing) , and I want that it's will be 5 too (namely, the output in type of char*)..
Quted from http://www.cplusplus.com/reference/fstream/ofstream/rdbuf/
std::ofstream::rdbuf
Returns a pointer to the internal filebuf object.
Notice however, that this is not necessarily the same as the currently
associated stream buffer (returned by ios::rdbuf).
When you construct an ostream object, you should specify the buffer, i.e. where to output. You can construct output as follows:
std::stringbuf buf;
std::ostream output(&buf);
Anyway, as Carl suggested in the comment, you don't need the intermediate object output, and simply do
ss << x;
Related
Below code is the normal way to get the input from a text and store it in an array in a structure.
Wanted to ask how can i use pointer to store all these data into the array of structure ? Like p1->Years (this is without array, but how can i apply this to way of writing in below code)
Any better suggestion to use pointer to take in the input?
int years = 4;
struct maju_company {
int Year;
float quarter1, quarter2, quarter3, quarter4, total_sales, average_sales;
};
int main() {
string line;
maju_company p1[years];
fstream yeecinnfile("MajuSales.txt");
if(yeecinnfile.is_open()) {
//ignoring the first four line of code and store the rest of the code
string line1,line2,line3,line4;
getline(yeecinnfile,line1);
getline(yeecinnfile,line2);
getline(yeecinnfile,line3);
getline(yeecinnfile,line4);
while(!yeecinnfile.eof()) {
for(int i =0; i<years; i++) {
yeecinnfile>>p1[i].Year>>p1[i].quarter1>>p1[i].quarter2>>p1[i].quarter3>>p1[i].quarter4;
}
}
for(int i =0; i<years; i++) {
cout<<p1[i].Year<<setw(10)<<p1[i].quarter1<<setw(10)<<p1[i].quarter2<<setw(10)<<p1[i].quarter3<<setw(10)<<p1[i].quarter4<<endl;
}
cout<<endl;
}
}
I see nothing wrong with the way you do this.
However, you could create a pointer to each record inside the loop
maju_company* p = &p1[i];
and then use p-> instead of p1[i]., but I really don't see this as an improvement.
If the reading loop looks too complicated, I would rather move the code to a separate function, perhaps
void read_record(maju_company& company);
or maybe
maju_company read_record();
and then only have to handle a single company inside the function (so no indexing and no ponters there).
I think you wouldn't need pointers at all for your example.
Use a std::vector to hold all your data and then there are other
things from C++ I think you should learn to use, example here :
(if you have questions let me know)
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
// dont use : using namespace std;
struct maju_company_data
{
int year;
float quarter1, quarter2, quarter3, quarter4, total_sales, average_sales;
};
// describe how to stream data to an output stream (like std::cout)
std::ostream& operator<<(std::ostream& os, const maju_company_data& data)
{
os << "-----------------------------------------------------\n";
os << "Company data for year : " << data.year << "\n";
os << "Quarter 1 : " << data.quarter1 << "\n";
os << "Quarter 2 : " << data.quarter1 << "\n";
os << "Quarter 3 : " << data.quarter1 << "\n";
os << "Quarter 4 : " << data.quarter1 << "\n";
os << "\n";
return os;
}
int main()
{
// no need to manage pointers yourself use a vector
std::vector<maju_company_data> company_yearly_data; // give variables a meaningful name
std::ifstream ifile("MajuSales.txt"); // ifstream your using file as input
std::string line1, line2, line3, line4;
// ignore first line
ifile >> line1;
while (ifile >> line1 >> line2 >> line3 >> line4) // probably you need to read a few more lines here
{
maju_company_data data;
// convert read strings to numbers
data.year = std::stoi(line1);
data.quarter1 = std::stof(line2);
data.quarter2 = std::stof(line3);
data.quarter3 = std::stof(line4);
//..
//data.quarter4 = std::stof(line5);
//data.total_sales = std::stof(line6);
company_yearly_data.push_back(data);
};
// this is a range based for loop
// it is prefered since you cant go out of bounds
// const auto& means that data will be an unmodifiable
// reference to each of the structs stored in the vector
for (const auto& data : company_yearly_data)
{
std::cout << data; // since we overloaded << this loop will be nice and clean
}
return 0;
}
A C++ approach to this to overload the istream operator>> and ostream operator<< for your specific type. E.g.
#include <algorithm>
#include <array>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
static constexpr auto years{4};
struct maju_company {
int Year{};
float quarter1{}, quarter2{}, quarter3{}, quarter4{};
float total_sales{}, average_sales{}; // ALWAYS init your floats.
};
auto& operator>>(std::istream& is, maju_company& mc) {
is >> mc.Year
>> mc.quarter1 >> mc.quarter2 >> mc.quarter3 >> mc.quarter4
>> mc.total_sales >> mc.average_sales;
return is;
}
auto& operator<<(std::ostream& os, maju_company const& mc) {
os << mc.Year
<< std::setw(10) << mc.quarter1
<< std::setw(10) << mc.quarter2
<< std::setw(10) << mc.quarter3
<< std::setw(10) << mc.quarter4;
return os;
}
You can then go on to use the type using the std library, e.g.
int main() {
auto p1{std::array<maju_company, years>{}};
{
auto fs{std::fstream("MajuSales.txt")};
if (!fs.is_open()) return -1;
{
// throw away 4 lines
auto dummy{std::string{}};
for (auto i{0}; i < 4; ++i) getline(fs, dummy);
}
std::copy_n(std::istream_iterator<maju_company>{fs},
years,
begin(p1));
}
std::copy(cbegin(p1), cend(p1),
std::ostream_iterator<maju_company>{std::cout, "\n"});
}
I'm trying to print an object Order (actually a vector of Orders). Order has some data members, including a vector with other objects, Purchase.
I can print the vector<Purchase> to cout on its own, and I can print vector<Objects> if I ignore the vector<Purchase> member. But the tricky part is to print vector<Objects> with vector<Purchase> included.
Here is my code:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
struct Purchase {
string name;
double unit_price;
int count;
};
struct Order {
string name;
string adress;
double data;
vector<Purchase> vp;
};
template<typename Iter> //this is my general print-vector function
ostream& print(Iter it1, Iter it2, ostream& os, string s) {
while (it1 != it2) {
os << *it1 << s;
++it1;
}
return os << "\n";
}
ostream& operator<<(ostream& os, Purchase p) {
return os << "(" << p.name << ", " << p.unit_price << ", " << p.count << ")";
}
ostream& operator<<(ostream& os, Order o) {
vector<Purchase> vpo = o.vp;
ostringstream oss;
oss << print(vpo.begin(), vpo.end(), oss, ", "); //This is what I would like to do, but the compiler doesn't like this conversion (from ostream& to ostringstream)
os << o.name << "\n" << o.adress << "\n" << o.data << "\n"
<< oss << "\n";
return os;
}
int main() {
ifstream infile("infile.txt");
vector<Order> vo;
read_order(infile, vo); //a function that reads a txt-file into my vector vo
print(vo.begin(), vo.end(), cout, "");
return 0;
}
As you can see, I had the idea to use ostringstreams as a temporary variable, that I would store the vector<Purchase> before I pass it on to the ostream& os. But this is a no go. What would be a good solution to this problem?
I am fairly new to C++ and are just learning the different uses of streams, so please bear with me if this is a stupid question.
Looks like you have two minor typos.
First, remove the indicated portion:
oss << print(vpo.begin(), vpo.end(), oss, ", ")
// ↑↑↑↑↑↑↑
Then, later in that same function, you cannot stream a stringstream, but you can stream the string serving as its underlying buffer, so use std::stringstream::str():
os << o.name << "\n" << o.adress << "\n" << o.data << "\n"
<< oss.str() << "\n";
// ↑↑↑↑↑↑
With those fixes in place, and the missing read_order function abstracted away, your program compiles.
The easiest way is to write an overload of operator<< that takes a const reference to a std::vector<Purchase> and then just stream the vector into the ostream:
std::ostream& operator<<(std::ostream& os, const std::vector<Purchase>& v);
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();
}
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
I should know this already but... printf is to sprintf as cout is to ____? Please give an example.
It sounds like you are looking for std::ostringstream.
Of course C++ streams don't use format-specifiers like C's printf()-type functions; they use manipulators.
Example, as requested:
#include <sstream>
#include <iomanip>
#include <cassert>
std::string stringify(double x, size_t precision)
{
std::ostringstream o;
o << std::fixed << std::setprecision(precision) << x;
return o.str();
}
int main()
{
assert(stringify(42.0, 6) == "42.000000");
return 0;
}
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
ostringstream s;
s.precision(3);
s << "pi = " << fixed << 3.141592;
cout << s.str() << endl;
return 0;
}
Output:
pi = 3.142
Here's an example:
#include <sstream>
int main()
{
std::stringstream sout;
sout << "Hello " << 10 << "\n";
const std::string s = sout.str();
std::cout << s;
return 0;
}
If you want to clear the stream for reuse, you can do
sout.str(std::string());
Also look at the Boost Format library.
std::ostringstream
You can use this to create something like the Boost lexical cast:
#include <sstream>
#include <string>
template <typename T>
std::string ToString( const T & t ) {
std::ostringstream os;
os << t;
return os.str();
}
In use:
string is = ToString( 42 ); // is contains "42"
string fs = ToString( 1.23 ) ; // fs contains something approximating "1.23"
You have a little misunderstanding for the concept of cout. cout is a stream and the operator << is defined for any stream. So, you just need another stream that writes to string in order to output your data. You can use a standard stream like std::ostringstream or define your own one.
So your analogy is not very precise, since cout is not a function like printf and sprintf