Thursday, July 9, 2009

C++ programming question?

Hi





In the code below i want to make it so that the user can enter 2 numbers but when i run the program the program will allow the user to enter only 1 number, even the code to enter a second number is present. I am not sure what i am doing wrong. Please do help!!!





#include %26lt;iostream%26gt;





using namespace std;





class Complex


{


public:


friend ostream %26amp;operator%26lt;%26lt;(ostream%26amp;, const Complex %26amp;);


friend istream %26amp;operator%26gt;%26gt;(istream%26amp;, Complex %26amp;);





private:


float real;


float imaginary;


};





ostream %26amp;operator%26lt;%26lt;(ostream %26amp;output, const Complex %26amp;c)


{


output %26lt;%26lt; c.real %26lt;%26lt; c.imaginary %26lt;%26lt; "i";


return output;


}





istream %26amp;operator%26gt;%26gt;(istream %26amp;input, Complex %26amp;c)


{


input %26gt;%26gt; c.real;


input.ignore();


input %26gt;%26gt; c.imaginary;





return input;


}





int main()


{


Complex number1, number2;





cout%26lt;%26lt;"Enter 1st number";


cin%26gt;%26gt;number1 %26gt;%26gt; number2;





cout%26lt;%26lt;"Enter 2nd number";


cin%26gt;%26gt;number2;





return 0;


}





I tried it doing two ways as you can see above


Thank you

C++ programming question?
I only modified main() like so:





int main()


{


Complex number1, number2;





cout%26lt;%26lt;"Enter 1st number: ";


cin %26gt;%26gt; number1;





cout%26lt;%26lt;"Enter 2nd number: ";


cin%26gt;%26gt; number2;


return 0;


}





Compiled OK, no warnings or errors.





Behavior: At run time, I had sucess, but I had to enter two numbers, each followed by return key at each prompt.


"Enter 1st number: " %26lt;I entered: 3, %26lt;enter key%26gt; I entered 4, %26lt;enter key%26gt;


Enter 2nd number: " %26lt;same again like above%26gt;





So... I had to enter 4 numbers total. Now, why is that?





I think it's because of this class implementation code portion:


istream %26amp;operator%26gt;%26gt;(istream %26amp;input, Complex %26amp;c)


{


input %26gt;%26gt; c.real;


input.ignore();


input %26gt;%26gt; c.imaginary;


}





See? Looks like there are 2 inputs for numbers there. This might explain it. cin is doing it's job based on the way the class is coded, ie: 2 inputs needed per cin prompt, when the object is handed to cin like so:





cin%26gt;%26gt;number1;





So, interesting, i think the runtime behavior is as coded and well-defined, just not what you expected...





...good luck...





EDIT: Outstanding! I see you got the rest/fix on your own! Good job, you!


No comments:

Post a Comment