Re: ostream outputting garbage
On Jan 3, 5:50 am, dev_15 <naumansulai...@googlemail.com> wrote:
Hi, i have the following program to display the input received
separated into any word that has Uppercase letters and all lowercase
words.
For the following input "Upper lower" i get the following
output on the console
Upper
0002A634lower
0002A634
I was expecting just
Upper
lower
Why am i getting the print of some memory address presumably, code
below:
Because thats what you asked it to do.
using std::string;
using std::vector;
using std::cin;
using std::cout;
using std::ostream;
using std::endl;
bool IsUpper(const string& s);
ostream& Write(ostream& out, vector<string>& v);
vector<string> GetUpper(vector<string>& v);
int _tmain()
int main()
{
vector<string> vec;
string s;
while (cin >> s)
vec.push_back(s);
read input indefinitely?
vector<string> Upper = GetUpper(vec);
cout << Write(cout, Upper);
cout << Write(cout , vec);
Write(...) is being used like an operator, or trying to rather.
Instead of streaming the results of a function, doesn't it make sense
to stream the object(s), in this case the elements in that
std::vector?
Why don't you define an operator<< to stream std::vector< T > instead?
( staggered for readability and untested code )
#include <algorithm>
#include <iterator>
// operator<< for std::vector< std::string >
std::ostream&
operator<<( std::ostream& out,
const std::vector< std::string >& v )
{
std::copy( v.begin(),
v.end(),
std::ostream_iterator< std::string >(out, "\n") );
return out;
}
// then:
std::cout << Upper << vec; // so simple, clean
To further improve the above insertion op, template the operator so it
works with std::vectors of any type, not just std::string. Try it -
it'll be eye opening. An operator that can stream a vector of
anything, including a vector of types that don't exist yet (hint:
std::string already has an overload for op<<, same goes with all
primitive types).
template< typename T >
std::ostream&
operator<<( std::ostream& out,
const std::vector< T >& v )
{
...
}
return 0;
}
ostream& Write(ostream& out, vector<string>& v)
{
for(vector<string>::size_type i =0; i!=v.size(); ++i)
{
out << v[i] << endl;
}
return out;
}
vector<string> GetUpper(vector<string>& v)
{
vector<string> Upper;
vector<string>::iterator iter = v.begin();
while (iter != v.end())
{
if (IsUpper(*iter))
{
Upper.push_back(*iter);
iter = v.erase(iter);
}
else
{
++iter;
}
}
return Upper;
}
bool IsUpper(const string& s)
{
bool ret = false;
typedef string::size_type string_size;
string_size i = 0;
while (i != s.size() && (ret==false))
{
if (isupper(s[i]))
ret = true;
++i;
}
return ret;
}