problems with scanf input stream

I am trying to do a postfix evaluation using stack. The output is supposed to be in a format
2,3,4,+,-,# with # signifying the end of expression. The problem is negative numbers are allowed i.e 2,3,-10,+,-,# is also a valid input. I need a method to separate the numbers from the characters.

int main() {
    int num;
    char ch;
    int ret;

    printf("Enter integers or characters separated by commas (e.g., 12,a,34,#):n");

    while (1) {

        scanf(" ,");

        ret = scanf("%d", &num);

        if (ret == 1) {
            printf("Input is an Integer: %dn", num);
            if (ret == -1)
                break;
        } else {
            if (scanf(" %c", &ch) == 1) {
                // Print an error message for non-integer input
                //ch = getchar();
                printf("Input is a Character: '%c' (invalid integer)n", ch);
            } else {
                printf("End of inputn");
                break;
            }
        }
    }

    return 0;
}

The problem I am facing is, if the input is 1,2,3,a,b,-1 -> it correctly identifies the numbers as numbers and a,b as characters. But if I give 1,2,3,+,-,#,-1 as input, it somehow takes , instead of + and - while recognizes #. I am at my wit’s end why this is happening. Any help is appreciated.

New contributor

Arka is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

11

The problem is scanf("%d", &num) only has one character look ahead. It reads the + sign and since that could start a number, it reads the next character to parse the number, but this character is a , so it pushes it back to the input stream and returns 0. Your version of scanf cannot push back more than one byte so the next byte read by scanf(" %c", &ch) is the ,, not the + sign. The same problem occurs for the - after the ,.

This behavior looks like a quality of implementation issue, but the C Standard actually specifies that a prefix of the expected form is read and dicarded, only the first byte that cannot be part of the match is left in the input stream. Hence the + sign and any preceding white space are consumed for the failing %d conversion. One more pitfall in the scanf family of functions that makes them difficult to use properly and makes error recovery unlikely.

scanf() is not the right tool for your project. fgets and strtol seem more appropriate and provide better error checking:

#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char buf[200];

    printf("Enter integers or characters separated by commas (e.g., 12,a,34,#):n");

    while (fgets(buf, sizeof buf, stdin)) {
        char *p;
        char *q;
        long num;
        char ch;

        for (p = buf; *p; p++) {
            if (isspace((unsigned char)*p)
                continue;
            errno = 0;
            num = strtol(p, &q, 10);
            if (q > p) {
                if (errno) {
                    printf("Input is an out of bound integer: %.*sn", (int)(q - p), p);
                } else {
                    printf("Input is an integer: %ldn", num);
                }
                p = q;
            } else {
                char ch = *p++;
                printf("Input is a character: %cn", ch);
                if (ch == '#')
                    break;
            }
            while (isspace((unsigned char)*p))
                p++;
            if (*p == ',')
                continue;
            printf("expected a comman");
            if (*p == '')
                break;
        }
    }
    return 0;
}

4

The issue is that the characters + and - may be part of a number, such as in -1, so in the case of these characters when scanf("%d", &num) fails to read an integer decimal number it will consume the + or - characters from the input, therefore the following scanf(" %c", &ch) ends up reading the separating comma as the input character.

One solution to this would be to first read each entry between commas , as a string and store it in a char array. And to do that you can use the specifier " %[^,n]" in the scanf function, which is the string specifier to discard leading blank characters, and store anything that is not a comma , or a new line character n in the char array.

And then you can use the sscanf function to process the string in the array, to find out if it is a valid int or a character.

Like this:

#include <stdio.h>

int main() {
    char string[100] = "";
    char ch = '';
    int num = 0;
    int ret = 0;
    
    while (scanf(" %99[^,n]", string) == 1) {
        if (sscanf(string, "%d", &num) == 1) {
            printf("Input is an Integer: %dn", num);
        }
        else if(sscanf(string, " %c", &ch) == 1) {
            printf("Input is a Character: '%c' (invalid integer)n", ch);
        }
        ret = scanf("%c", &ch);
        if (ret != 1 || ch == 'n') {
            printf("End of inputn");
            break;
        }
    }

    return 0;
}

Or, as suggested by @chux-ReinstateMonica, you could use strtol to process the string, like this:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char string[100] = "";
    char ch = '';
    char *end = NULL;
    long num = 0;
    int ret = 0;
    
    while (scanf(" %99[^,n]", string) == 1) {
        num = strtol(string, &end, 10);
        if (string < end && *end == ''){
            printf("Input is an Integer: %ldn", num);
        }
        else {
            printf("Input is a Character: '%s' (invalid integer)n", string);
        }
        ret = scanf("%c", &ch);
        if (ret != 1 || ch == 'n'){
            printf("End of inputn");
            break;
        }
    }

    return 0;
}

1

Reading user input and parsing is challenging. Often it is best to separate input from parsing as each have their own particular problems and recovery that do not work well together.

scanf() may not fully restore input that failed a scan.. Only 1 failed scanned character may be restored. After a failure, scanning again may pick up in unexpected places.


Input, then parse

Consider reading a token: a string up to the delimiter ',', EOF or max length.

char *read_token(size_t n, char token[n]) {
  if (n == 0) {
    return NULL;
  }
  n--;
  size_t i = 0;
  for (;;) {
    int ch = fgetc(stdin);
    if (ch == ',') {
      break;
    }
    if (ch == EOF) {
      if (i == 0) {
        return NULL;
      }
      break;
    }
    if (i >= n) {
      // Token too long
      return NULL;
    }
    token[i++] = (char) ch;
  }
  token[i] = '';
  return token;
}

After reading the token, parse it, multiple times, as needed.

#define N 1000
char buffer[N];
while (read_token(N, buffer)) {
  long num;
  char *endptr;
  errno = 0;
  num = strtol(buffer, &endptr, 0);
  if (endptr > buffer && errno == 0 && *endptr == '') {
    // We have a valid long.
    ...
    continue;
  }
  
  if ((strlen(buffer) == 1) && (buffer[0] == '-' || buffer[0] == '+'  || ...)) {
    // We have a single character operand.
    continue;
  }

  // look for end
  if (strcmp(buffer, "#") == 0) {
    // We are done
    break;
  }

  // Parsing failed everything.  
  Signal error with TBD code.
}

If obliged to use scanf("%d",..., scan for the sign first.

[ I like the @isnick better – making this wiki]

Something like

while (1) {
  unsigned char sign;
  scanf(" ,");  // TBD, add return value checking to all `scanf()`.
  scanf(" %c", &sign);  
  if (isdigit(sign)) {
    ungetc(sign);
    sign = '+';
  }
  if (sign == '-' || sign == '+') {
    if (1 == scanf("%d", &num)) {
      if (sign == '-') num = -num;
      printf("Input is an Integer: %dn", num);
      ...
    } else {
      // sign is the operand + or -
    }
  } else {
    // Test if `sign` is a valid operand + or /, etc.
  }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật