In Xcode 8.3 update, C/C++ programming printf does

2019-07-12 20:24发布

问题:

After last week's updated to Xcode 8.3, in a C/C++ program the output from a printf statement no longer appears on the screen without a newline. Thus I can't prompt for the user to enter a number, and have them type in that number on the same line following the input prompt.

Neither flushing the output buffer [fflush(stdout) or cout << endl] nor setting the output buffer to NULL [setbuf(stdout, NULL)] addresses this problem, but rather is a question specifically about Xcode 8.3 seemingly being broken.

With the scanf commented out, the output of the program below is:

Enter a value for x: Value of x is: 0

With the scanf in place, the output from the first printf never shows up. If you go ahead and type in a value and press enter, only then does it show up. Output is:

3
Enter a value for x: Value of x is: 3

Full test program is here:

#include <iostream>
using namespace std;

int main() {
    int x=0;
    printf("Enter a value for x: ");
    //scanf("%d", &x);

    printf("Value of x is: %d\n", x);
    return 0;
}

My work-around has been to revert back to Xcode 8.2.1, downloaded from developer.apple.com/xcode/downloads/

回答1:

8.3.2 was announced last night and addresses this supposedly:



回答2:

It is standard behavior in C for stdout to be flushed when an input function is called, such as scanf(), regardless of whether a newline was output prior to the call or not. This ensures that all appropriate output is displayed before the input operation takes place. Therefore, the update might have broken something in Xcode. Although I'm not currently sure what the exact nature of the problem is, a (temporary) workaround is to run your application on the command line. This has worked for my projects. It also reveals that this problem is with the Xcode output window, and not the compiler or something else.

In response to tell's comment: no, flushing stdout does not correct the issue within Xcode. This implies even more strongly to me that the issue is definitely in the Xcode interface itself. When running the application from the command line, calls to fflush() work as expected.

Also, printing to stderr makes no difference from within Xcode. Basically, stdout should be flushed in this case without appealing to stderr or any other gimmicks because the OP is calling scanf(). It works perfectly from the command line... just not in the Xcode output window.

And please note this this question is not a duplicate: it has nothing to do with anyone's misunderstanding of how C input and output work, and everything to do with the fact that a recent update to Xcode broke something.

EDIT:

Thanks, joe_04_04. The update certainly seems to have fixed the problem.