Re: namespaces conflict?
From: Rob Williscroft (rtw_at_freenet.co.uk)
Date: 10/20/04
- Next message: Aleks D: "testing"
- Previous message: Gianni Mariani: "Re: Reading specific memory address into variable"
- In reply to: Aleks D: "namespaces conflict?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 20 Oct 2004 04:33:41 GMT
Aleks D wrote in news:820e57f0.0410191959.5e79fbab@posting.google.com in
comp.lang.c++:
> Take a look at the following code:
>
> std::istream& operator>>(std::istream& in, char* str) {
You don't modify the str argument so make it char const *.
> int i=0;
> for (char c; str[i] && in.get(c) && c==str[i]; ++i)
> ; //get consumes the characters from the stream
> if (str[i]) {
> in.setstate(std::ios_base::failbit);
> std::cerr<<"problem with consuming"<<str; //debugging code
> }
> return in;
> };
>
> namespace SimpleSketch {
>
> istream& operator >>(std::istream& is, SimpleGraph& graph) {
> is>>"ImgWd = "; //line A
> /* .... */
> }
> }
>
> This code crashes on line A.
What's the crash
...
Ok got it, you're using the compiler in a non conforming mode
and its treating "ImgWd = " as a char *, it should be a const.
Then the compiler is calling std::operator >>( ... , char * ) which
overwrites the constant string and you get a crash, this is conforming
behaviour BTW.
> But if I put the definition of the
> operator >> inside the namespace SimpleSketch, it works.
> Unfortunately the code is in another file, so that makes things highly
> inconvenient. How can I make the caller code work without modifying or
> copying the source of the operator.
>
> I am programming on MSVC++.NET
>
#include <iostream>
#include <sstream>
std::istream& operator>>(std::istream& in, char const * str)
{
int i=0;
for (char c; str[i] && in.get(c) && c==str[i]; ++i)
; //get consumes the characters from the stream
if (str[i]) {
in.setstate(std::ios_base::failbit);
std::cerr<<"problem with consuming"<<str; //debugging code
}
return in;
};
int main()
{
std::istringstream iss( "Key = value" );
iss >> "Key = ";
char buf[ 10 ];
if ( !(iss >> buf) )
{
std::cout << "Arghhhhhhhh........\n";
}
else
{
std::cout << "[" << buf << "]\n";
}
}
The above works but I don't recomend it, be more explicit instead:
struct scanable
{
char const *str;
scanable( char const *s ) : str( s ) {}
};
std::istream operator >> ( std::istream &is, scanable const &scan )
{
// same as above but with scan.str substituted for str.
}
HTH.
Rob.
-- http://www.victim-prime.dsl.pipex.com/
- Next message: Aleks D: "testing"
- Previous message: Gianni Mariani: "Re: Reading specific memory address into variable"
- In reply to: Aleks D: "namespaces conflict?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|