_getch返回额外的null终止符

时间:2018-06-12 21:14:44

标签: c++

我从教程

获得了这个功能
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;
}

在输入每个字符后,它使用null终止符填充buf。

我必须像这样修改它才能使它工作:

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;
}

_getch()有什么问题?为什么它会不断返回null终止符?即使在工作函数中,如果我单步执行它,我会看到_getch()在每个字符输入后返回'\0' 3或4次。

编辑 - 我使用的是Visual Studio 2017.虽然这看起来像C代码,但是因为教程系列从教授cstrings开始,然后再转到std::string

1 个答案:

答案 0 :(得分:0)

事实证明Visual Studio 2017中存在一个带有_getch()的错误,导致在每个字符后插入空终结符。如果你从调试模式切换到发布模式,那么bug就会消失。

见这里:https://developercommunity.visualstudio.com/content/problem/252047/something-wrong-with-getch-in-loops.html