弹出随机字符

时间:2013-04-15 18:04:49

标签: c++

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

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),所以这不是问题,我在主方法上面有命名空间std。

2 个答案:

答案 0 :(得分: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';

答案 1 :(得分:0)

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

应该是

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

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