-2
#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;
}

This is a program that takes a polynomial(the first number of a pair is the coefficient,the second is the power) and compute its derivative in the same fashion.However,this program doesn't give me the intended result when I input 6 0 or 0 0,the result should be 0 0 in both cases. Additionally,I intend for this program to stop after one execution(one press of "Enter".How should I do that without changing entirely the code?

2 Answers2

0

Change while(scanf("%d %d",&a,&b)!=EOF) to while(scanf("%d %d",&a,&b)==2).

i486
  • 6,491
  • 4
  • 24
  • 41
0

You can

  1. Read full line via fgets()
  2. Parse the line via sscanf()
  3. During the parsing, use %n to read the number of bytes consumed and proceed to next token
#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;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70