user98188
user98188

Reputation:

Why does this program display seemingly random characters? (C++)

Well, not random, because its the same every time, but

#include<iostream>
using namespace std;
int main()
{
    char box[10][10];
    for(int i=-1;i<11;i++)
    {
        cout<<"---------------------"<<endl<<"|";
        for(int j=0;j<10;j++)
        {
            cout<<box[j][i]<<"|";
        }
        cout<<endl;
    }
    intx;cin>>x;
    return 0;
}

outputs a series of international characters (well, not all of them are 'international' per se, but I get things like pi and spanish inverted question mark). Anyways, I know this is becuase the program access chars that have not been initialized, but why do particular values create particular symbols, what are the ASCII values of the symbols (if they have ASCII values) and how can I get the symbols without glitching my program?

Upvotes: 0

Views: 3160

Answers (5)

Pekka
Pekka

Reputation: 3644

The symbols displayed by the program depend on:

  • the contents that happens to be in the uninitialised variables, and
  • the locale of your computer or the encoding used in presentation.

A Unicode reference would probably be the best source for identifying the codes required to display particular symbols.

Consider that your users may not have the same encoding (or fonts with the correct symbols) selected by default. You should either check the current locale, or force one specific to your output to ensure your output renders the way you wish.

Upvotes: 0

Dario
Dario

Reputation: 49208

The ASCII-code is

(int)(box[j][i])

You just print ordinary chars which are ASCII-characters with codes from 0 to 255. When printing wchar_ts the same memory is interpreted as other characters.

Your loop should be in [0; 10[ not in [-1; 11[

Upvotes: 0

anon
anon

Reputation:

For the same reason that

#include <iostream>
using namespace std;
int main()
{
   int x;
   cout << x;
}

displays a random value. Uninitialised variables (or arrays) contain garbage.

Upvotes: 2

user111593
user111593

Reputation: 241

for(int i=-1;i<11;i++)

That line is suspect. -1 to 10? Should be 0 to 9.

Upvotes: 0

Dan Olson
Dan Olson

Reputation: 23357

Your loop over i doesn't make sense...

for(int i=-1;i<11;i++)

This will hit two indices that aren't valid, -1 and 10, when you reference box here:

cout<<box[j][i]<<"|";

It should be 0 to < 10 like the other loop.

Also you haven't initialized the contents of box to anything, so you're printing uninitialized memory. You have to put something into your "box" before you can take anything out.

The symbols themselves are probably extended ASCII, you can get at them through any extended ASCII table. This one came up first on google. For instance, you could do:

cout << "My extended ascii character is: " << (char)162 << endl;

to get a crazy international o.

Upvotes: 3

Related Questions