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?
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.
a source to share
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.
a source to share