C 程序在 Windows 中运行良好,但在 Ubuntu 上运行时它不要求字符串?

Rav*_*jha 1 windows c c++

我用于从用户获取信息并打印相同的简单代码在 Windows 操作系统上运行良好(在 Dev C++ 上),但在 Ubuntu 上运行时它不要求字符串(通过 WINE/代码块尝试终端/开发 C++)

   #include<stdio.h>
   void display();
   struct book
  {
         int isbn;
         char name[25];
  }b[5];

   void PUSH()
   {
        int top;
        for(top=0;top<5;top++)
        {
        printf("Enter the ISBN no:");
        scanf("%d",&(b[top].isbn));
        printf("Enter the name:");
        fflush(stdin);
        gets(b[top].name);
        }
   }
  main()
  {
             PUSH();
             display();
  }
  void display()
  {
      int i;
      for(i=0;i<5;i++)
      {

      printf("----------------\nISBN no: %d",(b[i].isbn));
      printf("\nBook Name: %s \n",(b[i].name));
      }
      printf("----------------\n");
  }
  void POP()
  {
       int i;
      for(i=0;i<5;i++)
      {

      printf("----------------\nISBN no: %d",(b[i].isbn));
      printf("\nBook Name: %s \n",(b[i].name));
      }
      printf("----------------\n");

  }
Run Code Online (Sandbox Code Playgroud)

Ubuntu 上的输出:

   Enter the ISBN no:23
   Enter the name:Enter the ISBN no:
Run Code Online (Sandbox Code Playgroud)

在我输入 23 后,它必须询问书名,但跳过该部分并再次询问下一个 isbn no。

经过一些盲目的重试后,我发现当 gets(b[top].name); 获取(b[top].name);像这样使用了两次它工作得很好......

我的问题是为什么会这样。?如何让 ubuntu 编译和运行在 Windows 上运行良好的程序?

小智 6

这真的是因为你的 C 代码被破坏了,这不是 Ubuntu 或其他任何东西的错。

这里有一些关于如何修复它以使其正常工作以及如何编译它的提示。

  1. system("pause"); 不要这样做。避免系统调用,因为它们硬编码了终端系统的要求(Linux 上不存在)

  2. gets(b[top].name);应该替换为scanf("%s", &b[top].name);which 是一种更可靠的字符串输入方式。

  3. main()无效的,您应该替换main()int main()并替换system("pause");为简单的,return 0;以使您的 C 标准兼容。

如何编译

在 Linux 中编译比 windows 简单得多(对于像这样的小程序)。

  • 打开命令行。
  • cd ~/your/code/
  • 用这个命令编译: gcc -Wall --pedantic -o my_program my_program.c
    • 如果此命令失败,则需要运行 sudo apt-get install build-essential

最后是一些重要的建议: Dev C++ 于 2005 年消亡 - 在 Windows 上,切换到 Visual C++ 2010 Express,在 Linux 上使用 Eclipse 或文本编辑器和gcc命令。


希望这可以帮助