我尝试编译以下代码:
#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;
}真正重要的是这一部分:
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();
}
}程序应该显示一个文件的20行内容,但是当我在终端中运行它时,当它转到if-else部分时,它倾向于执行其他我放在answervariable.did中的东西,我做错了什么
注意:我已经用不同的编译器尝试过这段代码,比如lcc-win32,它工作得很好。
发布于 2012-06-28 23:57:44
不确定问题是什么,这是基于您的代码的配对q&d示例,并按预期工作。
#include <stdio.h>
int main(int argc, char * argv[])
{
char answer;
while(1) {
printf("\ndo you want continue:y=for continue/q=for quit: ");
fflush(stdin);
answer=getchar();
if(answer=='y' || answer=='Y')
puts("y/Y entered");
else if(answer=='Q' || answer=='q'){
puts("q/Q entered");
break;
}
else
puts("Something other than q/y entered.");
}
}不幸的是,我现在时间很紧,所以我不能检查你的版本和我的版本之间是否有任何实质性的差异。我什么都不记得了。
这是在Ubuntu下用gcc 4.4.3测试的。
看看这对你是否有效。
https://stackoverflow.com/questions/11254666
复制相似问题