Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

noob question c++

Name: Anonymous 2009-07-12 13:15

Why doesn't this work?

#include <iostream>
using namespace std;
int main(int argc,char** argv){
   string name;
   cout<<"What is your name?"<<endl;
   cin>>name;
   if(name=="Anonymous")
   cout<<"Aw don't be shy..."<<endl;
   else
   cout<<"Hello "<<name<<"!"<<endl
   return 0;
}

Name: Mr. I.H. BeaTty 2009-07-12 13:16

*raises eyebrow*
Really?

Name: Anonymous 2009-07-12 13:16

>>1
Oops there is a ';' after endl, I retyped it wrong.

Name: Anonymous 2009-07-12 13:20

>>3
Surely your compiler would have told you that

Name: Anonymous 2009-07-12 13:55

int main(int argc,char**argv){string name;cout<<"What is your name?"<<endl;cin>>name;if(name=="Anonymous"){cout<<"Aw don't be shy..."<<endl;}else{cout<<"Hello "<<name<<"!"<<endl;}return 0;}
Also stdio.h is superior.

Name: Anonymous 2009-07-12 14:38

>>4
retyped it
You jest.

Name: Anonymous 2009-07-12 19:47

Name: Anonymous 2009-07-12 19:52

so is == overloaded with c++ strings or not. is < and > overloaded? if so what is the point of the compare function.

Name: Anonymous 2009-07-12 20:03

>>8
OK, this is one of the countless pitfalls of C++. The == operator is overloaded for string, however what happens here is that your "name" string object is implicitly casted into a temporary integer yielding the address of the "name" object which is then compared to the address of the string literal "Anonymous". Obviously this is not what you want, so you'd have to explicitly cast "Anonymous" into a string object. Well you see C++ is full of crap like this, so you should just use a proper language like C# or Java.

Name: Anonymous 2009-07-12 20:29

>>9
More like you should subclass everything you plan to use, even the storage allocator, like a real man.

Name: Anonymous 2009-07-12 20:31

>>9
What the fuck? That's not what happens at all. There is no implicit cast from string to int; the compiler won't magically take the address of your string. There is an implicit cast from char* to string (due to string's implicit char* constructor), so that's what you will get, and the comparison will work.

You're thinking of comparing string* to char*. If you did this:

std::string* str = new std::string("Anonymous");
cout << (str == "Anonymous");

then yes, it would fail, because the pointers are compared, because in this case 'str' is a pointer type.

To answer >>8's question, yes == is overloaded (as well as < and >), and they will work comparing string to char*, but they will NOT work comparing string* to char*. You have to make sure you're not comparing pointers; if you have string pointers you have to dereference them.

But if you're doing things properly you should never, ever have string pointers anyway. If the overhead of copy constructors is a problem for you, you shouldn't be using stl string. In 99% of applications, the right thing to do is not worry about it and not let it bother you. Trust the compiler to do return value and related optimizations, and trust the allocator to do its job.

Name: Anonymous 2009-07-12 20:38

>>11 here, just to add to this:
Well you see C++ is full of crap like this, so you should just use a proper language like C# or Java.
Except epic failure, because == is NOT overloaded for Java. One of the first pitfalls I ran into with Java was trying to compare strings (and having someone explain to me that the Java VM is fucking stupidly comparing pointers).

Name: Anonymous 2009-07-12 20:49

>>11 and >>12 here again. I'm going to rant even fucking more about Java's == operator. It makes intuitive sense to compare objects with ==; you're testing whether they're the same instance. But with Strings, everything breaks. If you create several Strings from a literal, they will compare equal. If the user inputs the string, it will not compare equal to the literal. Now compound this with the fact that String is immutable. If you clone either of these, they WILL compare equal to the original, because clone is "return this" for immutable types. The whole thing is so fucking broken that == should not exist at all for objects that can be created as literals (String, Integer, etc), and should not exist at all for immutable types because the whole notion of 'instance' should not exist for immutable types.


To answer OP's question, your cin<<name is catching the trailing newline. It will work if you compare it to ("Anonymous" + endl).

Name: Anonymous 2009-07-12 20:55

>>13
Actually wait, wtf, it's not catching the newline... the code as written works perfectly for me (with compiler error fixed). What C++ library are you using?

Name: Anonymous 2009-07-12 20:57

>>13
get out of heer man you dont understand /prog/
/prog/ hates sepples and you are talking about it which further shits up /prog/
please get out

Name: Anonymous 2009-07-12 21:01

std::getline(name);

Name: Anonymous 2009-07-12 21:03

>>13
It makes intuitive sense to compare objects with ==; you're testing whether they're the same instance.
Even that isn't true, though. Conceptually, == tests object equality, because it works that way for primitives. This is in fact especially obvious for the primitives, which is why Sun tried to fix it by making the == operator compare by value for the primitive wrapper classes (except where they didn't), but it's conceptually the same for any kind of object. Having it test reference equality is just leaky abstraction.

Testing for object equality is much more common than testing for reference equality anyway, because most of the time you're comparing objects is when you're sorting them or when you're trying to match strings, so even without the conceptual break there's a good pragmatic argument for having == call .equals() and just having some immutable magic instance variable in the object representing its identity so people can compare reference equality using that.

Name: Anonymous 2009-07-12 21:05

>>11
So to restate what happens: string overloads == and the literal "Anonymous" is casted to string because string has a constructor that takes char*. The comparison works.  I have two questions then. 
1) If <, <=, > and >= are overridden, what purpose does string.compare serve other than redundancy?  Either use .compare and .equals (like java) or only use the overloaded operators.  The only reason I can think of is that they wanted to reimplemented C's strcmp for C++, but in that case why wouldn't they also re-implement functions such as atoi, and strtof which have to use c_str().

2) Is it standard to use == for string equality? I have string.compare(var)==0 all over some code that will be reviewed by people experienced in c++ ...

Name: Anonymous 2009-07-12 21:31

>>18
1. The C++ library is unusually redundant in some areas and completely lacking in others.

2. == yes, ==0 no. !string.compare(var) if you feel verbose, or just use ==.

Name: Anonymous 2009-07-12 21:32

>>17
But just because it's "more common" doesn't mean you can just get rid of reference equality; there are plenty of scenarios in which you do need it. You can't replace == unless you can give me a way of doing reference comparison. I agree that == should be a value comparison for immutable types (afaik C# sort of works this way?), except that now you have to know the details of a type before you can figure out whether == will do a value or reference comparison. This is the bigger problem with these languages like C# and Java which confound value and pointer types.

This is why I believe the C++ syntax works best in this respect. == is always a value comparison; it's just that the type of 'string*' is a pointer, with a pointer value, so comparing string pointers is a reference comparison. You only need to know the types of the variables you're comparing (is it string or string* ?), not the specification or implementation of the types themselves.

The real fix for this imho is that == in Java should always generate a compiler error for immutable types. This simplifies the syntax: == is always a value comparison for *primitives only*; always a reference comparison for everything else; and you are prevented from doing a reference comparison on types for which the result is undefined.

>>18
It makes sense for there to be a need for a compare function that can return >, == or < in the return value. This sort of stops making sense though when you realize that member function type is nonsensical, whereas it should be typed the same as a global function where an additional first argument is the object. Because of these type rules, you can't make a generic function that uses a compare function without templating it.

Lots of little things like this lead to the horrible templating that is STL.

Name: 17 2009-07-12 21:50

>>20
But just because it's "more common" doesn't mean you can just get rid of reference equality
Learn to read. I didn't suggest getting rid of reference equality, I suggested replacing it with the magic instance variable.

I agree that == should be a value comparison for immutable types (afaik C# sort of works this way?), except that now you have to know the details of a type before you can figure out whether == will do a value or reference comparison.
Which is just one reason my way is better.

The real fix for this imho is that == in Java should always generate a compiler error for immutable types. (...) and you are prevented from doing a reference comparison on types for which the result is undefined.
Great. So now programmers are forced to write comprehensive .equals() methods (or, god forbid, .hashCode()) just to be able to determine whether two differing mutable objects are the same objects, and they have no way of knowing whether two identical ones are different at all?
That's really going to improve that clusterfuck of a language.

Name: Anonymous 2009-07-12 22:08

>>20
The STL is fucking horrible. Another example I can think of is doing the equivalent of atoi() "the proper C++ way", which requires using strstream and its operator>>. If you take half an hour to trace through what code is actually generated by that, you'll see it creates around a dozen objects and several levels of calls deep, before finally doing the equivalent of atoi() (on g++, it uses strtoul().) It really makes you want to strangle whoever came up with the bloated piece of crap.

Name: Anonymous 2009-07-12 23:21

>>21
I didn't suggest getting rid of reference equality, I suggested replacing it with the magic instance variable.
Your "magic instance variable" idea does not work. The reason is because even though String is immutable, you can have any number of different String objects with the same content if they are created in different ways (e.g. literal Strings from the static string table vs. runtime-generated strings). So now you still need a full string check when the magic check fails (which will be virtually all of the time), only now you need a way of uniquely generating these magic checks.

All you've really given us is the address check optimization for operator==. Big deal.

Great. So now programmers are forced to write comprehensive .equals() methods (or, god forbid, .hashCode()) just to be able to determine whether two differing mutable objects are the same objects, and they have no way of knowing whether two identical ones are different at all?
What the fuck part of my post gave you that idea? == should be disabled for IMMUTABLE TYPES, because the comparison is undefined. It is literally not in the language specification how a Java VM should behave when using == to compare string objects with other string objects and with string literals; it's just an object comparison, and the VM is allowed to do whatever optimizations it wants with regard to String instances. It should be disabled for this very reason; it is not defined.

You of course need both comparisons for mutable objects. The result IS defined for these, and so reference comparison should obviously be allowed. Reading comprehension FTW.

The way to fix the language is to not have primitive types at all, like Smalltalk. Unfortunately Java wanted this "half way" idea between C++ and a proper fully object-oriented syntax in order to get good performance. We all know how well that turned out.

Name: Anonymous 2009-07-12 23:59

>>21
Magic instance variable
I don't see the appeal of this. I'd probably even prefer like Visual Basic (ugh), which has = and Is.

The way it works in C♯ is as follows: == on reference types tests reference equality by default, but can be overloaded. == on value types generates an error unless the struct overloads ==. There's also the Object.Equals() method, which every object (reference or value type) has. For reference types it tests reference equality; for value types is tests value equality. In both cases it can be overridden.

There's also two ways of making sure you're testing reference equality: cast one of the objects to object or use object.ReferenceEquals, which is a static method.

Oddly string isn't actually a value type, despite being immutable, it just overloads == and != and overrides Equals. Using the operators will probably be more efficient, since both arguments are known to be strings at compile-time.

In conclusion, C# somehow managed to be more screwed up than Sepples. On second thought, though, Sepples has `references' as well as pointers, so:
    A *a = new A(), *b = new A(), &ra = *a, &rb = *b;
    a == b; // probably false (reference equality)
    ra == rb; // value equality (A's operator ==())

which may not be obvious at first.

-------------------------------

I'm not a fan of operator overloading to the extent that Sepples does it, but == and != is common sense (arithmetic operators can help clarify code too). I'm also mostly fine with Haskell's mass of weird operators like f <^(+.+)^> g since they at least only have one meaning, whereas Sepples turns bit shifts into I/O.

Name: 17 2009-07-13 14:18

>>23
Your "magic instance variable" idea does not work. The reason is because even though String is immutable, you can have any number of different String objects with the same content if they are created in different ways (e.g. literal Strings from the static string table vs. runtime-generated strings).
What the fuck is wrong with you? What I suggested is that if a and b are strings, a == b would compare by value (or rather, by calling .equals() behind the scenes) and a.ref == b.ref would behave like a == b behaves currently.
The fact that you suck at grade-school-level reading comprehension honestly has no bearing on how workable that is.

What the fuck part of my post gave you that idea? == should be disabled for IMMUTABLE TYPES, because the comparison is undefined.
I guess I assumed you made a typo and just suggested a system that was naïve and broken, instead of one that was utterly useless and fucktarded. Your ``solution'' is the worst of both worlds: it leads even more verbose code and it doesn't fix the issue at hand at all.

>>24
The way it works in C♯ is as follows: == on reference types tests reference equality by default, but can be overloaded.
Operator overloading is a stupid idea, and in this case it's clearly a bad hack.
The real problem is that == checks reference equality by default. It's brain-damaged, and trying to patch it up with Sepples behavior doesn't solve shit.

There's also two ways of making sure you're testing reference equality: cast one of the objects to object or use object.ReferenceEquals, which is a static method.
The object.ReferenceEquals idea is basically my magic instance variable idea, only wrapped in a method instead of an instance variable. I'm fine with that.

Name: Anonymous 2009-07-13 14:53

try using getline(cin, name); instead of cin >> name. cin>>name captures a string until terminated by a space or newline character, while getline(); keeps going until you press enter.

Name: Anonymous 2009-07-13 16:48

Please keep in mind the enterprise theorem, All languages in widespread business use are shit.

I have a wonderful proof of this but the comment box is too small to contain it.

Name: Anonymous 2009-07-13 16:54

>>27
Fermat, you're late.

Name: Anonymous 2009-07-13 17:08

>>28
how could he have made that post when he's late?

Name: Anonymous 2009-07-13 17:22

>>29
I expect Fermat to be in most threads and at least before the post count hits double digits, is all.

Don't change these.
Name: Email:
Entire Thread Thread List