C++ not showing cout in Xcode console but runs perfectly in Terminal

随声附和 提交于 2019-11-26 21:30:33

问题


Basically i am running a simple program in 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;
}

I have seen different questions about cout need to be flushed and all std::cout won't print and Xcode debugger not showing C++ cout output. The Xcode debugger does not print cout until i put \n or endl. But, it works perfectly fine on terminal.

What if i had to use What is your age: and the user input age in the single line rather than the next line putting \n and endl?

This is what the Xcode debugger shows after build and run

This is when user inputs and it displays the result

This is on the terminal and this is what exactly what i need the output on the Xcode debugger.


回答1:


By doing some research, there seems to be bug on cin and cout stream on Xcode Version 8.3 Build 8E162 released on Mar 27, 2017. Degrading to Xcode Version 8.2.1 works like a charm.




回答2:


You already solved your problem yourself: std::cout uses buffered output and should always be flushed. You can achieve this by either using std::cout << "What is your age? << std::flush, by using std::cout.flush() or by adding a line break like std::endl which flushes implicitly.

A complete solution could look like this:

#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;
}


来源:https://stackoverflow.com/questions/43158839/c-not-showing-cout-in-xcode-console-but-runs-perfectly-in-terminal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!