Robert Reid
Robert Reid

Reputation: 35

Why is my C++ code adding nonsense to the end of my ASCII string?

I'm quite new to C/C++, and I'm putting together a bad knuckle tattoo generator to get used to using strings and seeded random values. The programme should initialise a 9-character string to hold the final knuckle tattoo, generate 2 random sequences of 4 letters using their ASCII values, and then output this to the console. This isn't meant to be particularly good or sexy, I'm just using it to get used to working with arrays and generating random values. This is the code:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void randomKnuckleTatt(char inputString[]);

void main()
{
    char knuckleTatt[9]; //Will hold final tattoo output

    srand((unsigned int)time(nullptr)); //Seeding rand(void)

    randomKnuckleTatt(knuckleTatt); //Generate a random knuckle tattoo and add to knuckleTatt
    cout << "Your bad knuckle tatt is:\n"
      << knuckleTatt << endl;
}

void randomKnuckleTatt(char inputString[])
{
    int i;
    int randomValue;

    for (i = 0; i <= 3; i++)
    {
        randomValue = int(double(rand()) / RAND_MAX * 25 + 65); //Generate random integer and fit to range
        randomValue = char(randomValue); //Cast as char
        inputString[i] = randomValue; //Assign random ASCII letter to array element
    }

    inputString[4] = char(32);

    for (i = 5; i <= 8; i++)
    {
        randomValue = int(double(rand()) / RAND_MAX * 25 + 65);
        randomValue = char(randomValue);
        inputString[i] = randomValue;
    }
}

So far, randomKnuckleTatt successfully generates a valid knuckle tattoo (ie. two four-letter words separate by a space) from random ASCII values and modifies the knuckleTatt array with these values. However, when knuckleTatt is printed to the console with cout, loads of nonsense ASCII characters are also printed. It always prints the characters contained in knuckleTatt, along with seven of "╠" (ASCII 204 in decimal, if that's not displaying properly for anyone), and then some more junk characters - for example, the most recent output was "UXDP TTKJ╠╠╠╠╠╠╠²┘▬*­¸╗".

I've added a break point in debug on cout << "Your bad knuckle tatt is:\n", and knuckleTatt only contains the 9 ASCII characters generated in randomKnuckleTatt.

Why is this happening, and how do I stop it?

Upvotes: 0

Views: 484

Answers (1)

RvdK
RvdK

Reputation: 19790

You forgot the room of the null terminator/character (\0) to terminate the character string. So make your array bigger and set the last value to \0.

Use std::string next time.

Upvotes: 3

Related Questions