c++双击输入,直到按下Enter键
c++ input double until Enter key is pressed
我有这段代码,它将用户输入的双精度加起来,并在用户输入负数时停止。我想改变它,这样当用户按下ENTER键时它就会停止,而不输入数字,这可能吗?如果有,是怎么做到的?
double sum = 0, n;
cout << endl;
do
{
cout << "Enter an amount <negative to quit>: ";
cin >> n;
if(n >= 0)
{
sum += n;
}
}while(n >= 0);
return sum;
使用getline()
如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
double sum=0.0;
while (1)
{
cout<<"Enter Number:";
getline(cin, s);
if (s.empty())
{
cout <<"Sum is: " <<sum;
return 0;
}
else
{
sum=sum+ stod( s );
}
}
return 0;
}
输出示例:
Enter Number:89
Enter Number:89.9
Enter Number:
Sum is: 178.9
我通常不这样做,因为这可能会变得混乱,特别是当你需要找到中位数或模式时。对于上面的代码,我将这样做。
double sum =0;
double n =0;
while(cin >> n) // this will keep going as long as you either enter a letter or just enter
{
sum += n; // this will take any input that is good
if(!cin.good()) // this will break if anything but numbers are entered as long as you enter anything other then enter or a number
break;
}
相关文章:
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- C++,Qt:仅在双击后编辑qtablewidget项目
- 双击更改 mfc 中列表控件中的行的颜色
- C++MFC编辑框处理双击
- 双击滑块手柄时如何发出信号
- C/C++ 检测双击 TVItem 的常用控件
- 在使用 c++ 的 win32 api 中,我想跟踪双击和三次单击等
- 在树状视图中双击后焦点丢失
- MFC功能区主页按钮双击关闭应用程序
- QGraphicsScene 中的 QPushButton 需要双击而不是单击
- 处理WM_POINTER消息时,如何检测双击/点击
- 双击编译C++ Unix 可执行文件不会打开现有文件以从中读取信息
- QListWidget 项目单击和项目双击 - 如果双击,则阻止单击
- 可执行文件无法在双击执行时创建新文件
- OS X 双击速度
- 双击(触摸)按屏幕按钮的原因可能是什么,该按钮通过单击鼠标按下
- 如何区分OpenCV中的点击和双击
- 在Windows中检测全局双击
- 如何在mfc中处理单击和双击同一按钮
- c++双击输入,直到按下Enter键