c++ avoiding overflow read into char array

43 Views Asked by At

am trying to make a program, in which the user has to input into different sizes char[] arrays. I am allowed to use string.h stdlib.h iostream libaries. how can I check if user input is bigger then Max size-1(to save place for /0), without asking first what the size and avoiding overflow crash. thank you

I tried to look up different things but they seems pretty complex to something that doesn't sound very complex, realized I can't use strings because it is in the string library

1

There are 1 best solutions below

2
MikeCAT On

You can read characters one-by-one and count the characters read.

#include <iostream>

void read_string(char* dst, size_t dst_size) {
    if (dst_size == 0) return;
    size_t size_read = 0;
    while (size_read + 1 < dst_size) {
        char c;
        if (!(std::cin >> c) || c == '\n') break;
        dst[size_read++] = c;
    }
    dst[size_read] = '\0';
}

int main(void) {
    char buf[16];
    read_string(buf, sizeof(buf));
    std::cout << buf << '\n';
    return 0;
}