【问题标题】:How to port code using Windows conio.h to Linux?如何使用 Windows conio.h 将代码移植到 Linux?
【发布时间】:2011-11-06 05:46:30
【问题描述】:

我为 Win32/c 编译器编写了这个 C 程序,但是当我尝试在 Linux 机器或 codepad.org 中使用 gcc 运行它时,它显示“conio.h:没有这样的文件或目录编译终止”什么是修改完成执行此程序而不包括任何其他新包含,如 curses.h

#include<stdio.h>
#include<conio.h>
void main()
  {
   int i=0,j=0,k=0,n,u=0;
   char s[100],c2,c[10];
   char c1[3]={'a','b','c'};
   clrscr();
   printf("no of test cases:");
   scanf("%d",&n);
  for(u=0;u<n;u++)
    {
 printf("Enter the string:");
 scanf("%s",s);
  i=0;
 while(s[i]!='\0')
  {
     if(s[i+1]=='\0')
         break;
     if(s[i]!=s[i+1])
     {
      for(j=0;j<3;j++)
       {
    if((s[i]!=c1[j])&&(s[i+1]!=c1[j]))
    {
      c2=c1[j];
     }
}
    s[i]=c2;

  for(k=i+1;k<100;k++)
    {
 s[k]=s[k+1];
}
  i=0;
  }
  else
  i++;
}
c[u]=strlen(s);

}
for(u=0;u<n;u++)
printf("%d\n",c[u]);
 getch();
}

【问题讨论】:

    标签: c include conio


    【解决方案1】:

    您在conio.h 中使用的函数似乎只有clrscr()getch()。只要把它们拿出来就可以了——它们似乎不会影响程序的运行。它们在这里的使用更像是 Windows 终端行为的解决方法。

    几点说明:

    1. main() 应该返回 int
    2. strlen()string.h 中定义 - 您可能想要包含它。

    【讨论】:

      【解决方案2】:

      查看您的问题,我可以看到对于 clrscr() 和 getch() 您正在使用 conio.h 但此标头在 gcc 中不可用。所以对于 clrscr 使用

      system("clear");
      

      正如你提到的 getch() 使用 curses 库

      干杯!!

      【讨论】:

      • 诅咒太过分了。 gets() 会很好。
      【解决方案3】:

      我没有看你的代码是否需要这三个函数。但这是获取它们的最简单方法。通常有比使用 getch() 更好的方法。清除我的屏幕时,clrscr() 也不好玩!

      #include<stdio.h>
      #include <stdlib.h>  // system
      #include <string.h>  // strlen
      #include <termios.h> // getch
      #include <unistd.h>  // getch
      
      void clrscr()
      { 
        // Works on systems that have clear installed in PATH
        // I don't like people clearing my screen though
        system("clear");
      }
      
      
      int getch( ) 
      {
        struct termios oldt, newt;
        int ch;
      
        tcgetattr( STDIN_FILENO, &oldt );
        newt = oldt;
        newt.c_lflag &= ~( ICANON | ECHO );
        tcsetattr( STDIN_FILENO, TCSANOW, &newt );
        ch = getchar();
        tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
        return ch;
      }
      

      getch()

      【讨论】: