c++ - “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()
也用于获取变量的值。它有其他用途而不是这个吗?
谢谢,
解决方案
像许多新手一样,您对types有点困惑。无论是什么类型,cin >> a
都会从cin
变量中读取,所以,等都可以使用. 这是一个简化,但现在已经足够接近了。a
a
float
int
std::string
>>
a = cin.get()
仅用于读取单个字符,它返回输入中的下一个字符。在您的第一个程序中发生的事情是将 char 值get()
转换为浮点值。跳过细节,但这不是很有意义的事情,这就是为什么你会得到奇怪的结果。
>>
和之间的另一个区别get()
是它>>
会跳过空格但get()
不会。因此,如果您想读取单个字符而不管它是否为空格,那么请get()
使用>>
.
推荐阅读
- asp.net-mvc - 新的 ASP.Net 项目,但要求登录
- apache-nifi - 使用 NIFI 将数据从 oracle 传输到 postgres
- visual-studio - Visual Studio 导航栏对象下拉菜单不起作用
- sql - 在 SQL 中将 1 行与多行进行比较
- asp.net-core - 使用 Azure Key Vault 的 ASP.NET Core 数据保护,用于将容器化应用部署到 Azure Kubernetes 服务
- regex - 保留原始消息并在正则表达式中提取捕获的字段
- sql - 从另一个 dblink 表中填充缺失的列值
- javascript - 如何使用 JavaScript 将完整的 HTML 字符串作为变量读取和更新
- python - PyO3 在 Rust 中实现 python 可迭代类
- java - 如何从自身更新android应用程序