2

i am supposed to read input from stdin in format like "%c %d:%d:%d %d" and allowed character at the beginning are + - #

what i have tried is

while(1){       
    ret = scanf(" %c %d:%d:%d %d",&c,&h,&m,&s,&id);
    if (ret != 5) break;

        if(c=='#') {
            log++;
            abs_prev=-1;
            continue;
        }else if(c=='+'){}
        else if(c=='-'){}
        else{
            printf("invalid input.\n");
            return 0;
        }
}

this code fails because when i enter input + 15:00:00 1enterbutton#enterbutton it puts \n character into the variable c which is not matched below and returns 0

here is what my input can look like + 8:00:00 100 + 8:50:00 105 - 9:30:00 100 - 18:20:00 105 - 19:00:00 100 # - 17:00:00 100 + 18:00:00 100 # # + 8:00:00 66 + 9:00:00 200 + 10:00:00 100 - 15:00:00 200 - 17:30:00 66

what i want to do with it is when first char is + i store data in tree A, if its - i will store it in tree B when its # i create new tree

2
  • You can change your scanf() as scanf(" %c %d:%d:%d %d %*c",&c,&h,&m,&s,&id); Commented Nov 23, 2014 at 17:05
  • ret = scanf(" %c %d:%d:%d %d",&c,&h,&m,&s,&id); ?. What is data type of ret ? Commented Nov 26, 2014 at 7:31

2 Answers 2

1

Read user input with fgets(), then scan it.

char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL)
  Handle_EOF();

// Note spaces before %d are not needed
int ret = scanf(" %c%d:%d:%d%d", &c, &h, &m, &s, &id);
if (ret == 1) {
  if (c != '#')
    Handle_InvalidInput();
  log++;
  abs_prev = -1;
} else if (ret == 5) {
  if (c != '+' && c != '-') {
    printf("invalid input.\n");
    return 0;
  }
} else {
  Handle_InvalidInput();
}
Sign up to request clarification or add additional context in comments.

Comments

1

You'd better to restructure your code since the input lines can be in different formats. The following code seems to be work for your purpose:

while (1){
    if (scanf(" %c", &c) != 1) break;

    if (c=='#') {
        log++;
        abs_prev=-1;
        continue;
    }

    ret = scanf("%d:%d:%d %d",&h,&m,&s,&id);
    if (ret != 4) break;

    if (c == '+') {}
    else if (c == '-') {}
    else {
        printf("invalid input.\n");
        return 0;
    }
}

Please be sure that the type of c should be char not an integer since its address is passed as an argument of scanf.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.