Home > Enterprise >  Ways for reading inputs in C without reading newline or using scanf
Ways for reading inputs in C without reading newline or using scanf

Time:06-18

I have a college exercise to do, that consists in writing a bank in C and I do know that scanf is a really buggy function and fgets reads the '\n', that I don't really want to be read. So I have written new functions trying to solve this problem:

char *readstr(char *buff, size_t bytes) {
    char *ptr;
    for (ptr = buff;
         (*ptr = getchar()) != '\n' && *ptr != EOF && ptr - buff < bytes - 1;
         ptr  )
        ;
    int c = *ptr;
    *ptr = '\0';
    if (c != EOF && c != '\n') {
        while ((c = getchar()) != '\n' && c != EOF)
            ;
    }
    return buff;
}

int readint() {
    char buffer[256] = "";
    readstr(buffer, 256);
    return atoi(strpbrk(buffer, "0123456789"));
}

double readfloat() {
  char buffer[256] = "";
  readstr(buffer, 256);
  return atof(strpbrk(buffer, "0123456789"));
}

char readchar() {
  char buffer[2] = "";
  readstr(buffer, 2);
  return *buffer;
}

until now, I wrote these ones. Any advice or suggestion? a more elegant one or simpler solution? apparently they work, but I don't know if this is the best approach.

CodePudding user response:

scanf is not buggy, it's simply hard to use correctly.

Anyway, you can use fgets and remove manually the newline character. A way to do this is by using the strcspn function like follows:

fgets(str, size, stdin);
str[strcspn(str, "\n")] = 0;

CodePudding user response:

Your goal seems to read a line of input into a buffer with a given size, not storing the trailing newline and discarding any excess characters present on the line. You do need to read the newline so it does not linger in the input stream, but you do not want to store it into the destination array as fgets() does.

Note that this can be achieved with scanf() this way:'

char buf[100] = "";
if (scanf("           
  • Related