gpt4 book ai didi

c++ - 为什么 "keep_window_open()"不等待输入字符?

转载 作者:太空狗 更新时间:2023-10-29 23:13:40 25 4
gpt4 key购买 nike

我是编程新手,我正在尝试自学 C++,我正在遵循“使用 C++ 进行编程的原则和实践”。

我正在尝试做一个练习,在执行其他各种步骤后,要求我做

" ...change the body of the loop so that it reads just one double each time around. Define two variables to keep track of which is the smallest and which is the largest value you have seen so far. Each time through the loop write out the value entered. If it’s the smallest so far, write the smallest so far after the number. If it is the largest so far, write the largest so far after the number".

到目前为止,我编写了以下代码:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open() { cout<<"\nType a character to exit: "; char ch; cin>>ch; }

int main()
{
double val1 = 0, smallest = 0, largest = 0;
int flag = 0;
while (cin >>val1) {
if (val1=='|')
break;
else
cout <<val1 <<'\n';
if (flag==0) {
smallest = val1;
cout <<smallest <<" it's the smallest value so far.\n";
}
if (val1<smallest) {
smallest = val1;
cout <<smallest <<" it's the smallest value so far.\n"; }
else if (val1>largest) {
largest = val1;
cout <<largest <<" it's the largest value so far.\n"; }
++flag;
}

keep_window_open();

return 0;
}

我的问题是当我输入一个字符时,例如'c',程序结束,虽然程序应该结束,假设只有当我输入 '|' 时,我得到:

c

Type a character to exit:
Process returned 0 (0x0) execution time : ...
Press any key to continue.

"keep_window_open()" 不等待输入字符。我只是不明白发生了什么,为什么。有人有线索吗?

最佳答案

嗯,我认为问题在于您定义循环表达式的方式。cin 及其运算符“>>”都不会返回您可以使用的 true/false 值。他们返回一个 iStream 对象,该对象可能是通过在幕后发生的自动转换可疑地转换为 true 或 false。然而,当无法在您的变量中设置输入时,它们将返回 null,例如尝试将“c”放入 double ,null 转换为 false。

我建议你创建一个简单的 while(true) 循环,当你得到“|”来自用户的字符(作为字符串)你打破了循环。直到那时循环继续。然后在循环内解析您的值并根据您的逻辑(最小值/最大值)对其进行处理

关于c++ - 为什么 "keep_window_open()"不等待输入字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37682683/

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