0

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

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 << "'s\n" ;
        strikes++;
    }
    else
    {
        cout << "There are " << numberOfLetters << " " << userInput << "'s\n";
    }
    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 缓冲区,但什么也没做。我也有所有必要的包含文件(字符串和 iostream),所以这不是问题,我在 main 方法上方有命名空间 std。

4

2 回答 2

0

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

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

如果您打算使用终止字符,则应该是

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

要不就

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() ] = '\0';
于 2013-04-15T18:11:36.340 回答
0
puzzle[inputPuzzle.size()+1] = '';

应该

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

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

于 2013-04-15T18:15:11.283 回答