随机出现的字符

Random characters popping up

本文关键字:字符 随机      更新时间:2023-10-16

当我调试程序时,当输出带星号的行时,它会输出随机的字符流。

int main ()
{
string inputPuzzle;
cout << "Enter a word or set of words: ";
getline(cin, inputPuzzle);
char* puzzle = new char[inputPuzzle.size()+1];
memcpy(puzzle, inputPuzzle.c_str(), inputPuzzle.size()+1);
puzzle[inputPuzzle.size()+1] = '';
int strikes = 0;
char userInput;
char* userSoln = new char[inputPuzzle.size()];
for (int i = 0; i < inputPuzzle.size(); i++)
{
    userSoln[i] = '-';
    if (puzzle[i] == ' ')
    {
        userSoln[i] = ' ';
    }
}
bool solved = false;
int numberOfLetters;
for (;;)
{
    numberOfLetters = 0;
    cin >> userInput;
    for (int i = 0; i < inputPuzzle.size(); i++)
    {
        if (userInput == puzzle[i])
        {
            numberOfLetters++;
            userSoln[i] = puzzle[i];
        }
    }
    if (numberOfLetters == 0)
    {
        cout << "There are no " << userInput << "'sn" ;
        strikes++;
    }
    else
    {
        cout << "There are " << numberOfLetters << " " << userInput << "'sn";
    }
    if (userSoln == puzzle)
    {
        break;
    }
    if (strikes == 10)
    {
        break;
    }
    **cout << "PUZZLE: " << userSoln << "n";**
    cout << "NUMBER OF STRIKES: " << strikes << "n";
}
if (strikes == 10)
{
    cout << "Sorry, but you lost. The puzzle was: " << puzzle;
}
else
{
    cout << "Congratulations, you've solved the puzzle!!! YOU WIN!!!!!";
    }
}

我试过清除cin缓冲区,但什么也没做。我也有所有必要的include文件(字符串和iostream(,所以这不是问题所在,而且我在主方法上方有命名空间std。

这不是一个有效的字符常量。

puzzle[inputPuzzle.size()+1] = '';

如果你想要一个终止字符,它应该是

puzzle[inputPuzzle.size()+1] = '';

或者只是

puzzle[inputPuzzle.size()+1] = 0;

或者您可以替换这两条线

memcpy(puzzle, inputPuzzle.c_str(), inputPuzzle.size()+1);
puzzle[inputPuzzle.size()+1] = '';

strcpy

strcpy(puzzle, inputPuzzle.c_str());

编辑:

在打印之前,您还需要在userSoln的末尾放置一个终止字符

userSoln[ inputPuzzle.size() ] = '';
puzzle[inputPuzzle.size()+1] = '';

应该是

puzzle[inputPuzzle.size()+1] = '';

您试图将null终止符添加到字符串的末尾以表示结束,但"不完全是。