4

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 what the Xcode debugger shows after build and run

This is when user inputs and it displays the result

This is when user inputs and displays the result

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

This is on the terminal

Community
  • 1
  • 1
AST
  • 1,549
  • 1
  • 13
  • 17
  • Considering that it works fine with terminal but not with xcode, I would look into the xcode compiler and linker options in the settings first... maybe you'll find something interesting there. – LPVOID Apr 01 '17 at 16:27
  • A new question http://stackoverflow.com/questions/43160533/xcode8-program-is-not-executing-correctly seems to have the same problem. – Bo Persson Apr 01 '17 at 19:05

2 Answers2

1

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;
}
dtell
  • 2,488
  • 1
  • 14
  • 29
  • still it does not print, `what is your age` , first rather it waits for an input from user and gives the same result like this 20 What is your ageMy age is 20 – AST Apr 01 '17 at 15:56
  • Does it work when you add a line break like `\n` or `std::endl` ? – dtell Apr 01 '17 at 16:02
  • yes it works, but i do want to print `what is your age` and ask input to the user on a same line rather than the next line. – AST Apr 01 '17 at 16:03
  • Hm, all resources I've found so far tell that XCode won't output until the line is terminated by a line break. A really strange behavior! Sorry, but I have no other solution. – dtell Apr 01 '17 at 16:30
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.

AST
  • 1,549
  • 1
  • 13
  • 17