【问题标题】:The program fails to display `cout` when it is run程序运行时无法显示“cout”
【发布时间】:2011-01-15 18:35:00
【问题描述】:

我刚开始学习 C++ 课程,我编写、编译、调试并运行了我的第一个程序:

// This program calculates how much a little league team spent last year to purchase new baseballs.
#include <iostream>
using namespace std;

int baseballs;
int cost;
int total;
int main()
{
    baseballs, cost, total;

    // Get the number of baseballs were purchased.
    cout << "How many baseballs were purchased? "; 
    cin >> baseballs;

    // Get the cost of baseballs purchased.
    cout << "What was the cost of each baseball purchased? ";
    cin >> cost;

    // Calculate the total.
    total = baseballs * cost;

    // Display the total.
    cout << "The total amount spent $" << total << endl;
    return 0;
}

我遇到的唯一问题是,当我运行程序时,它无法显示总花费 (cout)。有人可以解释一下原因吗?

谢谢

杰夫 H - 佛罗里达州萨拉索塔

【问题讨论】:

  • 请编辑、突出显示您的代码并按 { } 按钮以正确格式化。

标签: visual-c++


【解决方案1】:

您的程序在我的系统(Mandriva Linux 2010.1 64 位)上运行良好。

在 Windows 中开发执行文本 I/O 的简单程序时,一个常见问题是运行它们的控制台 (cmd.exe) 窗口将在程序终止时自行关闭。这会阻止开发人员/用户读取程序的最终输出。也许这就是你的情况?

编辑:

在 Visual Studio 2010 上确认。窗口在您阅读输出之前关闭。如果您添加,则可以解决此问题

system("pause");

just read an empty input line 在 return 语句之前。请记住,system("pause")“技巧”是特定于 Windows 的,我确实推荐它,尽管它的输入速度稍快。

编辑 2:

我尝试了reading an empty input line,我意识到您实际上可能需要阅读 行这样的行,因为您在输入缓冲区中已经有一个剩余的换行符,而最后一个 @ 尚未检索到987654325@声明。

【讨论】:

  • 感谢您的反馈,thkala。
  • SilverbackNet - 所以我应该用粗体突出括号 {}? Jim Lewis - 我重新编译并运行了几次程序。我相信 thkala 提到的: cmd.exe 窗口在程序终止之前关闭。这可能是原因。
  • @Jeff:仅供参考,StackOverflow 有一个用于 cmets 的通知系统,通过在此人的句柄前添加一个“@”来触发,就像我在这里所做的那样。 (我认为句柄的前 3 个字符就足够了。)但我不确定一个评论中的多个通知是否有效,因此您可能希望分别对每个人发表评论。欢迎来到 SO!
【解决方案2】:

您可以在查看输出后在 return 语句之前添加另一个 cin 以结束程序。 Thkala 的逻辑是正确的。

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多