首页 > 解决方案 > “cin>>”与“cin.get”有何不同?或者不是吗?

问题描述

我正在为乘法表编写程序......我使用a=cin.get();andcin>>a;来输入值。我得到了不同的结果。代码是:

#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;
}

另一个是:

#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;
}

那个cin>>a;工作得很好。我曾经读过它cin.get()也用于获取变量的值。它有其他用途而不是这个吗?

谢谢,

标签: c++outputcin

解决方案


像许多新手一样,您对types有点困惑。无论是什么类型,cin >> a都会从cin变量中读取,所以,等都可以使用. 这是一个简化,但现在已经足够接近了。aafloatintstd::string>>

a = cin.get()仅用于读取单个字符,它返回输入中的下一个字符。在您的第一个程序中发生的事情是将 char 值get()转换为浮点值。跳过细节,但这不是很有意义的事情,这就是为什么你会得到奇怪的结果。

>>和之间的另一个区别get()是它>>会跳过空格但get()不会。因此,如果您想读取单个字符而不管它是否为空格,那么请get()使用>>.


推荐阅读