SwervinPervan
SwervinPervan

Reputation: 15

Random characters popping up

When I debug my program, it outputs a random stream of characters when outputting the asterisked line.

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

I've tried clearing cin buffers, but nothing doing. I have all the necessary include files (string and iostream) too, so that isn't the issue, and i have the namespace std above the main method.

Upvotes: 0

Views: 179

Answers (2)

Drew Dormann
Drew Dormann

Reputation: 63912

This isn't a valid character constant.

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

If you intended a terminating character, it should be

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

or just

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

or you could replace both these lines

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

with strcpy

strcpy(puzzle, inputPuzzle.c_str());

Edit:

You also need to put a terminating character at the end of userSoln before printing it.

userSoln[ inputPuzzle.size() ] = '\0';

Upvotes: 0

Rapitor
Rapitor

Reputation: 176

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

should be

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

you were trying to add the null terminator to the end of the string to signify the end, but '' is not quite it.

Upvotes: 0

Related Questions