Issue
I was coding a program for Multiplication Tables... And I used a=cin.get();
and cin>>a;
to input the value. I got different results with each. The code is:
#include"pch.h"
#include<iostream>
using namespace std;
int main()
{
float a, b;
cout << "Enter the number:";
a = cin.get();
cout << "The Table for the given number is:" << endl;
for (b = 1; b <= 10; ++b)
{
cout << a << " * " << b << " = " << a * b << endl;
}
return 0;
}
And the other one is:
#include"pch.h"
#include<iostream>
using namespace std;
int main()
{
float a, b;
cout << "Enter the number:";
cin >> a;
cout << "The Table for the given number is:" << endl;
for (b = 1; b <= 10; ++b)
{
cout << a << " * " << b << " = " << a * b << endl;
}
return 0;
}
The one with cin>>a;
worked fine.
I once read that cin.get()
is also used to get the value of the variable. Does it have some other use instead of this?
Thanks,
Solution
Like many newbies you're a bit confused about types. cin >> a
will read from cin
into variable a
no matter what type a
is, so float
, int
, std::string
etc all work with >>
. That's a simplification but close enough for now.
a = cin.get()
is for reading single characters only, it returns the next character in the input. What's happening in your first program is that a char value from get()
is being converted to a float value. Skipping over the details but that's not something that makes a lot of sense, which is why you get the strange results.
Another difference between >>
and get()
is that >>
will skip whitespace but get()
will not. So if you want to read a single character irrespective of whether it's whitespace or not then use get()
otherwise use >>
.
Answered By - john Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.