【问题标题】:different behavior xcode and Dev-C++不同的行为 xcode 和 Dev-C++
【发布时间】:2012-01-31 13:50:31
【问题描述】:

刚开始学习 C。
如果我在 Dev-C++ 中编译以下代码,程序运行良好。
如果我在 Xcode 3.2.6 中编译,它看起来像在屏幕截图中。
我在 Xcode 中尝试了不同的编译器设置,但行为仍然相同。
对此有何想法?

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

【问题讨论】:

  • 什么截图?无需添加屏幕截图,只需在您的问题或预期输出和实际输出中添加错误消息即可。

标签: c xcode3.2


【解决方案1】:

我的猜测是它与system("PAUSE"); 语句有关。 Xcode 用于 OSX,它是一个 UNIX 变体,并且没有命令 pause

为什么不直接要求用户手动按下回车键呢?像这样:

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

它具有适用于大多数系统的优势。

【讨论】:

    【解决方案2】:
    fflush(stdin);   
    

    导致未定义的行为,因此您的程序在不同的编译器上显示不同的行为。

    参考C标准:

    int fflush(FILE *ostream);
    

    ostream 指向未输入最近操作的输出流或更新流,fflush 函数会导致该流的任何未写入数据被传递到主机环境以写入文件; 否则,行为未定义。

    【讨论】:

    • 这是正确答案。看起来两个编译器都符合 C 标准并且行为正确,因为当从程序调用未定义的行为时,它们都会给出任何类型的随机结果。另请参阅C FAQ
    【解决方案3】:

    PAUSE 是 Windows,而不是 Unix 命令...所以在 Mac 上不起作用。如果您只想在最后暂停程序,请改用 getchar() 之类的东西。

    【讨论】:

      【解决方案4】:

      包含一个头文件Conio.h,并在你想按住屏幕时使用getch()函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-10
        • 2022-01-27
        • 2015-07-03
        • 2017-12-14
        • 2021-05-29
        • 1970-01-01
        • 2020-12-02
        • 2018-06-18
        相关资源
        最近更新 更多