Coding Discussion Forum
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Go down
avatar
rockstar
Admin
Posts : 5
Join date : 2020-02-15
https://codeforum.forumotion.com

100 days of code Empty 100 days of code

Sat Feb 15, 2020 3:05 pm
Please post all the new concepts and problems you have faced in this forum which will save time of the others.
avatar
Steve roger
Posts : 1
Join date : 2020-02-15

100 days of code Empty Re: 100 days of code

Sat Feb 15, 2020 8:52 pm
Hey there thanks for inviting
avatar
rockstar
Admin
Posts : 5
Join date : 2020-02-15
https://codeforum.forumotion.com

100 days of code Empty Re: 100 days of code

Mon Feb 17, 2020 6:38 pm
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

template <class T>
T addall(vector <T>list){
T count=0;
for(auto &c:list)
count+=c;

return count;
}

template <>
string addall(std::vector<string>list){
int count=0;
for(auto &c:list){
for(auto &l:c)
count+=l;}

ostringstream ostr;
ostr<<count;
return ostr.str();
}

int main() {
vector <int> vector_int{2,3,4,5,6,7};
vector <double> vector_double{2.0,3.0,4.0,5.0,6.0,7.0};
vector <string> vector_string{"abc","bcd","cde"};

cout<<addall(vector_int)<<endl;
cout<<addall(vector_double)<<endl;
cout<<addall(vector_string)<<endl;

return 0;
}

//////////////////////////////////////////////////////////

output:-
27
27
891
avatar
rockstar
Admin
Posts : 5
Join date : 2020-02-15
https://codeforum.forumotion.com

100 days of code Empty its just about library

Mon Feb 17, 2020 6:40 pm
The highly under-rated iostream library provides a much better option, in the form of ostringstream. This class provides a buffered stream, and returns us a std::string containing the information we have streamed to it. Because it is an iostream, we can pass any type into it so long as a stream handler exists for it. I'm not going to cover writing your own in this article, but it is really is very easy to do, and then you can stream any types you may create.

So the basic idea is that we create an ostringstream and then pass information into it, like this:


ostringstream strstrm;
strstrm << "This is how I pass in text, but I can pass in numbers as easily - "
<< 42 << endl;

We can then access the underlying string using the str() method, which we can chain to the strings c_str() method to get a const char * if desired. The
avatar
rockstar
Admin
Posts : 5
Join date : 2020-02-15
https://codeforum.forumotion.com

100 days of code Empty go here for more information

Mon Feb 17, 2020 6:40 pm
Sponsored content

100 days of code Empty Re: 100 days of code

Back to top
Permissions in this forum:
You cannot reply to topics in this forum