Reputation: 3447
I got this function from a tutorial
void read( char* buf, int maxSize ) {
const char* const pEnd = buf + maxSize;
for ( char c = _getch(); c != 13 && (buf + 1 < pEnd); c = _getch(), buf++ ) {
_putch( c );
*buf = c;
}
*buf = 0;
}
It filled buf with null terminators after each character was entered.
I had to modify it like this to make it work:
void read( char* buf, int maxSize ) {
const char* const pEnd = buf + maxSize;
char c = 0;
while ( c != 13 && (buf < pEnd) ) {
c = _getch();
if ( c != 0 ) {
_putch( c );
*buf = c;
buf++;
}
}
*buf = 0;
}
What is wrong with _getch()
? Why does it return null terminators constantly? Even in the working function if I step through it, I can see _getch()
returning '\0'
3 or 4 times after each character is typed.
EDIT --
I'm using Visual Studio 2017. While this looks like C code, it's because the tutorial series starts by teaching cstrings before moving on to std::string
.
Upvotes: 0
Views: 336
Reputation: 3447
It turns out there's a bug in Visual Studio 2017 with _getch() which causes null terminators to be inserted after every character. If you switch from debug to release mode the bug goes away.
Upvotes: 1