gpt4 book ai didi

windows - gcc 和 lccwin32 :different result

转载 作者:太空宇宙 更新时间:2023-11-04 09:50:51 24 4
gpt4 key购买 nike

我尝试编译这段代码:

#include <stdio.h>

void print(FILE *a)
{
int main();
int count=20;
int c;
int stop=0;
char answer;

while(!stop){
while((c=getc(a))!=EOF){
fprintf(stdout,"%c",c);
if(c=='\n'){
count--;
if(!count){
printf("do you want continue:y=for continue/q=for quit");
fflush(stdin);
answer=getchar();
if(answer=='y' || answer=='Y')
count=20;
else if(answer=='Q' || answer=='q'){
printf("you quit this program,press any key and hit the enter to close");
stop=1;
break;
}
else{
printf("argument is unacceptable,rolling back action");
main();
}
}
}
}
if(c==EOF)
stop=1;
}
}
void halt()/*do nothing just for halt and waiting for input*/
{
int a;

scanf("%d",&a);
}
int main()
{
FILE *in,*fopen();
char name1[25];
int a;

printf("enter the name of the file you want to show:");
scanf("%24s",name1);
in=fopen(name1,"r");
if(in==NULL){
printf("the files doesnt exist or it is in another directory, try to enter again\n");
main();
}
else
print(in);

fclose(in);
halt();

return 0;
}

该程序的目的是显示一个文件的 20 行内容。我在 windows xp 中用 lccwin32 编译了它,它按预期工作。但是当我将我的操作系统更改为 linux (Ubuntu:pricise pangolin 12.04 LTS Desktop) 并用 gcc 编译它时出现问题。首先它似乎工作正常但是直到第 20 行和提示符结束,当我把参数(y 表示继续,q 表示退出)并按回车键,但没有任何反应。它只是溜到 else 部分,该部分重新启动程序。所以是我的 gcc 有问题还是我的代码不适合 gcc 或者我可能错过了什么?

最佳答案

我讨厌 scanf。我建议将 scanf("%24s",name1) 替换为 fgets(s,24,stdin);(然后不幸的是做 if (s[strlen(s)-1] == '\n') s[strlen(s)-1] = '\0' 来摆脱最后的\n。

我还建议:

  1. 不在 main 上使用递归
  2. 使用 int main(int argc, char *argv[]) 然后将你的文件名作为参数传递(所以你会检查 argc > 1 然后使用 argv[1] 作为文件名,然后在运行程序时执行 ./programname 文件名)
  3. 仍然没有使用 scanf

关于windows - gcc 和 lccwin32 :different result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11246047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com