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

标签 c++ iostream

我是编程新手,我正在尝试自学 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/

相关文章:

c++ - 如何通过实例方法使用 C++11 线程?

c++ - 有没有办法在一段时间内阻止 cin 输入,然后再次允许输入?

c++ - 我应该在我的 C++ 程序中混合使用 C 和 C++ 风格的 I/O 吗?

c++ - 来自 file_descriptor_source (boost::iostreams) 或文件的 istream

C++,cin如何从输入缓冲区读取?

c++ - 在 C++ 11 中使用 Homebrew 软件、gcc 和 llvm

c++ - 如何在 C 中以较低的时钟速度运行程序

C++ QList继承自定义方法问题

c++ - 为什么 iostream 对象不重载 operator bool?

c++ - F1后跳转到QtCreator中正确的C++ STL文档页面?