2

我对编程并不陌生,但我对 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++ 中没有跨平台的睡眠功能,所以这不是一个选择。我还能做些什么来完成这项工作?

4

2 回答 2

4

你可以加

cin.ignore(1);

或者

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

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

此外,您既不需要比较 to 的返回值,get也不需要'\n'将其放入循环中。用户必须按回车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()一个循环并将其返回值与 进行比较,那么在遇到an 之前\n也存在到达文件结尾的危险。我相信这对您的程序的影响将是一个无限循环,但我不确定,因为我无法在 Windows 上尝试它。cin\n

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

while (true)
    if (cin.get() == '\n') break;
于 2011-09-02T23:31:00.893 回答
0

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();
于 2011-09-03T00:05:05.117 回答