different behavior xcode and Dev-C++

943 Views Asked by At

Just beginning to learn C.
if I compile the following code in Dev-C++ the program runs fine.
If I compile in Xcode 3.2.6 it looks like in the screenshot.
I tried different compiler settings in Xcode but the behavior is still the same.
Any ideas on this?

 #include <stdio.h>
 #include <stdlib.h>

 int main(int argc, char *argv[])
 {
     char artist[30];
     char album[30];
     int  tracks;
     char albumsingle;
     float price; 

     printf("Please enter CD informations below. \n \n");

     printf("enter cd artist: ");
     scanf("%[^\n]", artist);

     printf("enter cd title: ");
     fflush(stdin);
     scanf("%[^\n]", album);

     printf("enter no. of tracks: ");
     fflush(stdin);
     scanf("%d", &tracks);

     printf("enter a for album s for single: ");
     fflush(stdin);
     scanf("%c", &albumsingle);

     printf("enter price: ");
     fflush(stdin);
     scanf("%f", &price);



     printf("\n\n\nartist: %s\n", artist);
     printf("album: %s\n", album);
     printf("track no.: %d\n", tracks);
     if (albumsingle == 'a'){
         printf("cd type: album\n");
     } else {
         printf("cd type: single\n"); 
     }

     printf("price: %.2f EUR\n\n", price);                                 

     system("PAUSE");   
     return 0;
 }
4

There are 4 best solutions below

1
On
fflush(stdin);   

Causes an Undefined Behavior, and hence your program shows different behavior on different compilers.

Reference C standard:

int fflush(FILE *ostream);

ostream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

0
On

My guess is it has to do with the system("PAUSE"); statement. Xcode is used on OSX, which is a UNIX variant, and doesn't have the command pause.

Instead why not just ask the user to press the enter key manually instead? Like this:

printf("Press the ENTER key to continue.\n");
int c;
do
{
    c = fgetc(stdin);
} while (c != '\n' && c != EOF);

It has the advantage of working on most systems.

0
On

PAUSE is a Windows, not a Unix command ... so that won't work on the Mac. Use something like getchar() instead if you just want to pause the program at the end.

0
On

Include a header file Conio.h and use getch() function whenever you want to hold screen.