第一次运行此程序后,如何使其停止执行


#include<stdio.h>
/*input: 3 4 -5 2 6 1 -2 0
output:12 3 -10 1 6 0*/
int main(){
int a,b;
int flag=0;
while(scanf("%d %d",&a,&b)!=EOF){
if(b!=0){
if(flag==0)printf("%d",a*b);
else printf(" %d",a*b);
printf(" %d",b-1);
flag=1;//if b==0,this loop performs nothing.
}
}
if(flag==0)printf("0 0");
return 0;
}

这是一个采用多项式(对的第一个数是系数,第二个数是幂(并以相同方式计算其导数的程序。然而,当我输入6 0或0 0时,这个程序并没有给我预期的结果,在这两种情况下,结果都应该是0 0。此外,我打算让这个程序在一次执行后停止(一按"Enter"。我应该如何在不完全更改代码的情况下做到这一点?

while(scanf("%d %d",&a,&b)!=EOF)更改为while(scanf("%d %d",&a,&b)==2)

您可以

  1. 通过fgets()读取整行
  2. 通过sscanf()解析线路
  3. 在解析过程中,使用%n读取消耗的字节数,然后继续下一个令牌
#include<stdio.h>
/*input: 3 4 -5 2 6 1 -2 0
output:12 3 -10 1 6 0*/
int main(){
char line[8192];
while(fgets(line,sizeof(line),stdin)!=NULL){
int pos=0, delta;
int a,b;
int flag=0;
while(sscanf(line+pos,"%d %d%n",&a,&b,&delta)==2){
pos+=delta;
if(b!=0){
if(flag==0)printf("%d",a*b);
else printf(" %d",a*b);
printf(" %d",b-1);
flag=1;//if b==0,this loop performs nothing.
}
}
if(flag==0)printf("0 0");
putchar('n');
}
return 0;
}

相关内容

最新更新