utilizing cin.get()

Aug 6, 2012 at 10:18pm
hi Everybody, Im totally new in working with c++, and i got stuck I think in some stupidity I cant find out what it is. I dont know what is going on wrong with the next code.
it is supposed to tell if a given integer is even, but it doesnt!!!
#include <cmath>
#include <conio.h>
#include <iomanip>
#include <string>
int main()
{
int grade;

cout << "Enter the letter grades." << endl
<< "Enter the EOF character to end input." << endl;

while((grade = cin.get())!= EOF)
{
if (grade==0)
cout <<"Por Favor inserte un numero que no sea zero";
else
{
if(fmod(static_cast<double>(grade),2)==0)
cout << "Number is even";
else
cout << "Number is not even";
}
}
system("pause");

}
Aug 6, 2012 at 10:26pm
cin.get() will not skip white space characters like new line characters. You should probably use operator>> to read grade from cin instead.
Aug 7, 2012 at 1:24am
why are you using the EOF,, i believe EOF only used when you working with infile

when you getting your numbers from a txt..

you would use this

while (!infile.eof()

other wise if you using the cin window where you enter the values

"<< "Enter the EOF character to end input." << endl;"

you need to set a flag for the cin to end

i would use something like this


while (number <0)

so if you enter a -1 it would end the loop..

Aug 7, 2012 at 3:08am
you would use this while(!infile.eof())
No, you shouldn't.
Loop on the reading operation, or you would end with an extra reading depending if you file ends with a line break
So use while(input>>value)

The standard input and files are streams, you could mark eof too (in linux with <C-d>)

if(fmod(static_cast<double>(grade),2)==0) you may use operator % instead
Topic archived. No new replies allowed.