string_length 按退格键且字符串小于 0 c++ 时出错

string_length error when pressing backspace and string is less than 0 c++

当我退格并且字符串小于 0 时,应用程序显示以下错误

我使用的代码如下:

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <conio.h>
#include <string>

using namespace std;

int main()
{
    std::string a = "";

    char c;

    for (int i = 0; i < 1000; i++)
    {
        c = _getch();

        if (c == '\r')
            break;

        if (c == 8)
        {
            cout << '\b';
            cout << ' ';
            cout << '\b';

            a.resize(a.length() - 1);
        }
        else
        {
            cout << "*";
            a += c;
        }
    }

    return 0;
}

能请教一下吗?

编辑

我已将我的代码更改为以下内容,但现在当我按退格键时,它不允许对程序进行任何输入。

if (!a.empty())
{
    if (c == 8)
    {
        cout << '\b';
        cout << ' ';
        cout << '\b';

        a.resize(a.length() - 1);
    }
    else
    {
        cout << "*";
        a += c;
    }
}
else
{
    continue;   
}

不要调整到零以下...这看起来很简单。编辑-也就是说,在减小大小之前检查字符串是否为空。