gpt4 book ai didi

c++ - 我的问题 = 直到用户按下 "enter"从 C++ 中的用户输入取平均值

转载 作者:行者123 更新时间:2023-11-28 01:14:14 26 4
gpt4 key购买 nike

此代码计算从用户输入整数到用户输入“666”整数的平均值。但是,我想让它在用户按下回车键时停止。我怎样才能做到这一点?

#include <iostream>

using namespace std; //s

int main()

{
int total = 0, counter = 0, number, average;

do
{


cin >> number;
if(number == 666) //what should i do to make enter button instead of 666?
{
average = total / counter;
cout << average;
return 0;

}
total = total + number;
counter = counter + 1;

} while(1);

return 0;

}

最佳答案

遗憾的是,如果 <ENTER> 无法轻松检查按钮已被按下。 cin读取格式化输入(在你的情况下是数字)并忽略其他所有内容(包括空格,如换行符)。解决您的问题的方法是读取整行并从中提取数字:

#include <iostream> // cin, cout
#include <sstream> // istringstream
#include <string> // getline

int main()
{
// Reading a line from the standard input to the variable 'line'.
std::string line;
std::getline(std::cin, line);

// The easiest way to get the numbers from 'line' is to wrap it in an
// 'istringstream'. Now, you can use 'iss' just like 'cin'.
std::istringstream iss{line};

double total = 0.0;
double counter = 0.0;
for (double number; iss >> number; ++counter) {
total += number;
}
std::cout << "Avarage: " << total / counter << '\n';

return 0;
}

关于c++ - 我的问题 = 直到用户按下 "enter"从 C++ 中的用户输入取平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59223886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com