how protect against char array input out of bounds

Im trying to write a chess program. its supposed to take 4 characters as input from the console. so for example a2a3 to move the pawn from the bottom left up one space. The only way i know how to take this sort of input is with a char array but the problem here is that the input goes out of bounds if the user enters 5 characters and the program breaks. How do i solve this problem or if im going about it the wrong way in a more general sense what should i do differently? i know i could just set the size of the array to 1000 or something but that's a stupid solution.
Just use a string and you won't have to worry about the size you allocate.
1
2
3
4
std::string input;
std::getline(std::cin, input);
if(input.size() > 4) // too many characters
// etc. 
thanks ill try it
strings are cool

But you can use an array without breaking the program, too.

Andy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstring>
using namespace std;

int main() {
    const size_t input_size = 5; // 4 chars + null term
    char input[input_size];
    bool exit = false;
    do {
        while(!cin.getline(input, input_size)) {
            cout << "bad input" << endl;
            cin.clear();
            cin.ignore(1024, '\n');
        }
        if(0 == strcmp(input, "exit"))
            exit = true;
        else
            cout << "input = " << input << endl;
    } while(!exit);
    return 0;
}

Last edited on
thanks andy. if you dont mind me asking what does the size_t mean in line 6?
i ended up going with

1
2
3
4
5
6
int main(){
	string sInput;
	do {
		std::cin >> sInput;
	} while (sInput.size() != 4);
}
Last edited on
That will work if you only want to read until the first whitespace character, not necessarily the first newline.
The c style getline has a length argument:
http://www.cplusplus.com/reference/istream/istream/getline/

size_t, ( and if you follow that link, streamsize ) are unsigned integrals. Their size ( in bytes ) is machine/compiler dependent.
Topic archived. No new replies allowed.