在紧密循环中使用 cin.get()

发布于 2024-12-02 15:28:56 字数 909 浏览 0 评论 0原文

我对编程并不陌生,但对 C++ 比较陌生。我想分发简单的控制台应用程序,以便我可以在学习时帮助其他人。我大学校园里的绝大多数机器都是基于Windows的,并且默认安装了Borland编译器。我更喜欢使用 g++ 和其他工具在基于 Linux 的系统上进行开发。所以我想添加一些跨平台的方法来让程序一直运行直到用户按下回车键。这样,即使用户双击该 exe,而不是在 Windows 的控制台中运行它,也可以查看输出。为此,我编写了类似的内容:

#include <iostream>

using namespace std;

int main()
{

    float val1, val2;
    bool wait = true;

    cout << "Please enter the first value to add: ";
    cin >> val1;
    cout << "Please enter the second value to add: ";
    cin >> val2;
    cout << "Result: " << val1 + val2 << endl << endl;

    cout << "Press enter to exit...";

    while (wait)
    {
        if (cin.get() == '\n')
            wait = false;
    }

    return 0;
}

使用上面的代码,程序在显示结果后退出。但是,如果您注释掉 cin 调用,它就会按预期工作。这让我相信 cin.getline 正在从我上次的数据输入中获取我的回车键。我怀疑这是由于循环的紧密性造成的。我了解到 C++ 中没有跨平台的睡眠函数,所以这不是一个选择。我还能做些什么来完成这项工作?

I'm not new to programming, but I am relatively new to C++. I would like to distribute simple console applications so I can help others as I learn. The vast majority of machines on the campus of my university are windows based, and have the Borland compiler installed by default. I prefer to do my development on a Linux-based system with g++ and other tools. So I'd like to add some cross-platform way of leaving the program running until the user presses enter. That way, the user is able to view the output even if he or she double clicked on the exe rather than running it in the console in windows. To do this, I wrote something similar to:

#include <iostream>

using namespace std;

int main()
{

    float val1, val2;
    bool wait = true;

    cout << "Please enter the first value to add: ";
    cin >> val1;
    cout << "Please enter the second value to add: ";
    cin >> val2;
    cout << "Result: " << val1 + val2 << endl << endl;

    cout << "Press enter to exit...";

    while (wait)
    {
        if (cin.get() == '\n')
            wait = false;
    }

    return 0;
}

Using the code above, the program exits after displaying the result. However, if you comment out the cin calls, it works as expected. This leads me to believe that cin.getline is picking up my enter key press from my last data entry. I suspect this is due to the tightness of the loop. I have learned that there is no cross-platform sleep function in C++, so that is not an option. What else can I do to make this work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

复古式 2024-12-09 15:28:57

您可以

cin.ignore(1);

添加或

cin.ignore(INT_MAX, '\n');

在调用 cin.get() 之前 。这将忽略用户输入第二个数字或缓冲区中的所有字符留下的换行符,直到换行符为止。

此外,您既不需要将 get 的返回值与 '\n' 进行比较,也不需要将其放入循环中。用户必须按 Enter 键才能返回 get,因此

cout << "Press enter to exit...";
cin.ignore(INT_MAX, '\n');
cin.get();

就足够了。


如果这样做会发生什么

cout << "Press enter to exit...";
while (wait)
{
    if (cin.get() == '\n')
    wait = false;
}

:进入循环并调用 cin.get() 。用户可以根据需要在控制台输入任意数量的文本。假设他们进入了

Hello

控制台。然后用户按 Enter 键。 cin.get() 返回 H,并且 ello\n 仍保留在缓冲区中。将 H\n 进行比较,发现它们不相等,继续循环。调用 cin.get() ,由于缓冲区中已有文本,因此立即返回 e 。这个循环会继续浪费时间,直到到达缓冲区的最后一个字符,即 \n 并将其与 \n 进行比较,因此循环中断。正如您所看到的,这是浪费时间。

如果你确实将 cin.get() 放入循环中并将其返回值与 \n 进行比较,则还存在 cin 的危险> 在遇到 \n 之前到达文件结尾。我相信这对你的程序的影响将是一个无限循环,但我不确定,因为我不能在 Windows 上尝试它。

此外,即使您一开始不需要使用循环,但使用 bool 会浪费更多时间,因为您可以将循环减少到

while (true)
    if (cin.get() == '\n') break;

You can add

cin.ignore(1);

or

cin.ignore(INT_MAX, '\n');

before you call cin.get(). This will ignore the newline left from the user entering the second number or all the characters in the buffer until a newline.

Also you neither need to compare the return value of get to '\n' nor put it in a loop. The user has to hit enter for get to return, so

cout << "Press enter to exit...";
cin.ignore(INT_MAX, '\n');
cin.get();

Is sufficient.


What happens if you do

cout << "Press enter to exit...";
while (wait)
{
    if (cin.get() == '\n')
    wait = false;
}

Is that the loop is entered, and cin.get() is called. The user can enter any amount of text at the console as he wants. Say they entered

Hello

in the console. Then the user presses the Enter key. cin.get() returns H, and ello\n is still left in the buffer. You compare H with \n and see that they are not equal, continue the loop. cin.get() is called and since there is already text in the buffer, returns e immediately. This loop continues wasting time until it gets to the last character of the buffer which is \n and it compares true with \n so the loop breaks. As you can see, this is a waste of time.

If you do put cin.get() in a loop and compare the return value of it with \n, there is also the danger of cin coming to an end-of-file before an \n is encountered. I believe the effect of this on your program would be an infinite loop, but I'm not sure since I can't try it on Windows.

Also, even though you don't need to use a loop in the first place, you are wasting even more time with a bool because you could reduce the loop to

while (true)
    if (cin.get() == '\n') break;
不弃不离 2024-12-09 15:28:57

cin >> 之后,您应该忽略缓冲区中的所有字符,直到 '\n' 为止,

#include <limits> // for std::numeric_limits as indicated by Marlon

std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

然后您可以等待下一行:

cout << "Press enter to exit...";
cin.get();

After cin >> you should ignore all the characters in the buffer until the `\n' with

#include <limits> // for std::numeric_limits as indicated by Marlon

std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

Then you can wait for the next line with:

cout << "Press enter to exit...";
cin.get();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文