cin >> m; // this expects integer
if (!cin)
{ ... }
The documentation says:
"cin can only process the input from the keyboard once the RETURN key has been pressed. Therefore, even if you request a single character, the extraction from cin will not process the input until the user presses RETURN after the character has been introduced." http://www.cplusplus.com/doc/tutorial/basic_io/
However, when I press enter, I am still in the console window - even if I type ENTER multiple times, it just creates the paragraphs.
MyClass m;
/*
Pokud zadáš něco jiného než číslo bude výsledek chybý!
*/
cout << "Cekam objekt (enter number)" << endl;
cin >> m;
But seriously, you input a MyClass object, for which you overloaded operator>>.
I am very sure the problem is in the overload, but it is not defined in the code that you posted.
Sorry, guys, I forgot to send code from myClass.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14
std::istream& operator >> (std::istream &is, MyClass &objekt)
{
int cislo;
is >> cislo; // Využiji již přetížených operátorů pro primitivní datové typy
objekt.setA(cislo);
is >> cislo;
objekt.setB(cislo);
return is; // Nezapomeňte na tuto drobnost! Jinak nebudete moc dávat operátory za sebe
}
std::ostream& operator << (std::ostream &os, MyClass &objekt)
{
return (os << objekt.A << objekt.B); // Krátké, že?
}
Well clearly it's waiting for the user to give two numbers, not one! Try this:
1 2 3 4 5 6 7 8 9 10 11
std::istream& operator >> (std::istream &is, MyClass &objekt)
{
int cislo;
std::clog << "Dejte první číslo: ";
is >> cislo; // Využiji již přetížených operátorů pro primitivní datové typy
objekt.setA(cislo);
std::clog << "Dejte druhý číslo: ";
is >> cislo;
objekt.setB(cislo);
return is; // Nezapomeňte na tuto drobnost! Jinak nebudete moc dávat operátory za sebe
}
Otherwise, you could try giving two numbers at the same time, like:
#include "stdafx.h"
#include "MyClass.h"
usingnamespace std; // using istream and ostream
int main(void)
{
MyClass m;
/*
Pokud zadáš něco jiného než číslo bude výsledek chybný!
*/
cout << "Enter 2 numbers: (sumbit with ENTERs)" << endl;
cin >> m;
if (!cin)
{
cerr << "Object not loaded! " << endl;
}
else
{
ofstream f("data.txt");
if (!f)
{
cerr << "Cannot open data.txt" << endl;
return -1;
}
f << "Entered numbers:" << endl << m;
cout << "Entered numbers:" << endl << m;
}
getch();
return 0;
}