C++ 在 Xcode 控制台中不显示 cout 但在终端中运行完美

标签 c++ xcode debugging cout

基本上我在Xcode Version 8.3 (8E162) 中运行一个简单的程序

#include <iostream>
using namespace std;
int main() {
    int a;   
    cout << "What is your age: ";
    cin >> a;
    cout << "My age is " << a << endl;
    return 0;
}

我看到了关于cout 需要刷新的不同问题,所有std::cout won't printXcode debugger not showing C++ cout output .在我输入 \n 或 endl 之前,Xcode 调试器不会打印 cout。但是,它在终端上工作得很好。

如果我不得不使用 What is your age: 并且用户在单行中输入年龄,而不是在下一行输入 \n 和 endl,该怎么办?

这是 Xcode 调试器在构建和运行后显示的内容

This is what the Xcode debugger shows after build and run

这是用户输入并显示结果的时候

This is when user inputs and displays the result

这是在终端上,这正是我需要在 Xcode 调试器上输出的内容。

This is on the terminal

最佳答案

您已经自己解决了问题:std::cout使用缓冲输出并应始终刷新。您可以通过使用 std::cout << "What is your age? << std::flush 来实现此目的, 通过使用 std::cout.flush()或添加一个换行符,如 std::endl隐式刷新。

完整的解决方案如下所示:

#include <iostream>

using namespace std;

int main() {
    int a;   
    cout << "What is your age: " << flush;
    cin >> a;
    cout << "My age is " << a << endl;
    return 0;
}

关于C++ 在 Xcode 控制台中不显示 cout 但在终端中运行完美,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158839/

相关文章:

c++ - 为什么一个代码编译而另一个失败?

c++ - glfw openGL c++ 窗口背景和标题

ios - 单独的类来存储输入

c++ - 这个c++代码有什么问题

Xcode Debugger-如何在CPU指令级别单步执行

c++ - 如何使用 SFINAE 选择最接近的匹配类型特征?

c++ - 参数传递转换 float 错误

ios - 如何将整数发送到类型 id 的指针

iphone - UILabel 多组值

c# - 禁用调试输出