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

Well, no coincidence, because it's 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 number of international characters (well, not all of them are "international" as such, but I get things like pi and Spanish inverted question mark). Anyway, I know this is because the program access characters were not initialized, but why do specific values ​​create certain characters, what are the ASCII character values ​​(if they have ASCII values) and how can I get characters without crossing my program?

0


a source to share


5 answers


Your loop over I makes no sense ...

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

      

This will remove the two invalid indices -1 and 10 when you reference here:

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

      

It should be between 0 and <10, just like in the other loop.



Also you haven't initialized anything for the field content, so you are printing uninitialized memory. You must put something in your "box" before you can do anything.

The characters themselves are probably ASCII extended, you can get them through any extended ASCII table. This one first appeared on google. For example, you can do:

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

      

to get crazy international o.

+3


a source


For the same reason that

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

      



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

+2


a source


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

This line is suspicious. -1 to 10? Must be between 0 and 9.

0


a source


ASCII code

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

      

You just print regular ones char

, which are ASCII characters with codes from 0 to 255. When you print wchar_t

, the same memory is interpreted as different characters.

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

0


a source


The symbols displayed by the program depend on:

  • content that is in uninitialized variables, and
  • the language of your computer or the encoding used in the presentation.

A Unicode reference will probably be the best source for identifying the codes needed to display certain characters.

Please note that your users may not have the same encoding (or fonts with the correct characters) selected by default. You should either check the current locale or force it to your output to ensure that your result looks the way you want it to.

0


a source







All Articles