console outputs smiley face - c++

I have this code:
#include "stdafx.h"
#include <iostream>
typedef struct{
int s1;
int s2;
char c1;
char* arr;
}inner_struc;
int _tmain(int argc, _TCHAR* argv[])
{
inner_struc myinner_struct;
myinner_struct.s1 = myinner_struct.s2 = 3;
myinner_struct.c1 = 'D';
char arr[3] = {1,2,3};
myinner_struct.arr = arr;
std::cout << "first array element: " << myinner_struct.arr[1] << std::endl;
return 0;
}
I wonder why am I getting a smiley face instead of the first array element! what am I doing wrong here? It compiles and runs fine however the output is
first array element: "smiley face"
What does this means?
I am using Visual Studio 2010. Thanks

You are outputing the second element in this array:
char arr[3] = {1,2,3};
You have assigned it the values 1 2 and 3, but the variable is of type char, so it is being interpreted as ascii. If you look up what character has a value of 2 on an ascii chart, you will see that it is a smily face. So it is indeed doing what you asked it to do.
http://mathbits.com/MathBits/CompSci/Introduction/ASCIIch.jpg
What are you expecting the output to be? if you wanted it to be a number, then you will have to add the character representation of that number into the array. ie in stead of 1, 2 or 3 use '1', '2', and '3'

As far, as I can see, you are trying to output the first array element. But instead, you are printing the second one (the arrays are indexed starting from 0, not 1). The second element is 2. Now, please, take a look at this table, as you can see: the number 2 is a smiley face. The problem is that you are outputing a character with code 2, not '2'. In order to output a deuce, make your array look like this:
char arr[3] = {'1','2','3'};

inner_struct.arr is declared as char *, which means it holds an array of characters (bytes). Do you want an array to hold the numbers 1, 2, 3? If so, use int. If you want letters, initialize the array with:
char arr[3] = { 'a', 'b', 'c' };
KC

Related

C++ Why is the output of this code 3? (structs)

Can someone help me understand step-by-step why the following C++ code outputs a 3?
#include <iostream>
using namespace std;
struct sct
{
int t[2];
};
struct str
{
sct t[2];
};
int main() {
str t[2] = { {0,2,4,6}, {1,3,5,7} };
std::cout << t[1].t[0].t[1];
}
t[1] is {1,3,5,7}.
str is represented in memory as four integers back-to-back, organized into 2 sct structures. In this case, the first one has the values 1 and 3, while the second contains 5 and 7.
Thus, t[1].t[0] is {1,3}, so t[1].t[0].t[1] is 3.
str t[2] = { {0,2,4,6}, {1,3,5,7} };
This means we are an array of two str values {0,2,4,6} at 0 index and {1,3,5,7} at index 1.
cout<<t[0] //gives 0,2,4,6
cout<<t[1] //gives 1,3,5,7
Now, when in question cout << t[1].t[0].t[1]; we see what is in t[1] i.e (1,3,5,7), and with that we go inside the str block to assign t[1] to a variable of type stc. Inside it there, we find another variable t[2] of type stc. Here we divide our previous value as t[1].t[0]=1,3 and t[1].t[1]=5,7.
Now, when in question cout << t[1].t[0].t[1]; we see what is in t[1].t[0]=1,3, and with that we go inside the stc block to assign t[1].t[0] to a variable of type int. Inside it there, we find another variable t[2] of type int. Here we divide our previous value as t[1].t[0].t[0]=1 and t[1].t[0].t[1]=3.
Now, when in question cout << t[1].t[0].t[1]; we see what is in t[1].t[0].t[1]=3, and then it gets printed due to cout!!!!!

setting char arrays equal to eachother with isdigit and isalpha

Im trying to set a char array equal to 2 other arrays depending on if the element in the first array is a number or a letter. The code makes logical sense to me but the output for the 2 other strings after the for loop doesn't correspond to the logic. Is it because of a missing null value somewhere in the other 2 loops or is the code itself invalid? arrayAlpha, arrayNum, and palind are all char arrays set to a length of 30 elements while string length was already determined before the for loop began.
for(int k=0; k<=stringLength; k++)
{
if( isalpha(palind[k])){
arrayAlpha[k]=palind[k];}
if ( isdigit(palind[k]))
{
arrayNum[k]=palind[k];
}
}
Given the input:
char palind[30] = "12345abcde";
arrayAlpha is garbage.
arrayNum is "12345"
However,
char palind[30] = "abcde12345";
arrayAlpha is "abcde".
arrayNum is garbage.
Thus, [k] is the problem when used in your arrayNum or arrayAlpha which doesn't start with 0.
Simple change will just be subtracting the length of the other.
arrayAlpha[k - strlen(arrayNum)] = palind[k];
arrayNum[k - strlen(arrayAlpha)] = palind[k];
since lengthOfPalind = lengthOfArrayAlpha + lengthOfArrayNum assuming palind only contains letters or numbers.

Is there a way to initialize arrays with mixed chars and "strings"

I would want to initialize char array during compilation time with least amount of manual work.
Is there a working shorthand format for this
char arr[5] = {0x4, 'a', 's', 'd' 'c'};
such as
char arr[5] = {0x4, "asdc"};
You could integrate the char int the string with escape sequences:
char arr[6] = { "\x04asdc"};
edit: corrected the wrog length of the array.
No that's not possible. But you could do
char arr[] = "\04asdc";
The problem with this is that is would not be exactly like the original array you show, since it would include the string terminator and therefore have six elements.

Understanding multidimensional string array in C++

I am new to c++. I can not understand why the following code prints the "r" string. I think the it should be an array of 2X3X4 elements, so by pointing to the arr[0][0][0] i would expect the first char in the first string of the first arr=a, but this prints abcd. Can anyone explain it?
#include <iostream>
using namespace std;
int main()
{
string arr [2] [3] [4]={
{"abcd","efgh","ijkl"},
{"mnop","qrst","xywz"}
};
cout<<arr [1] [0] [1] [1]<<endl;
return 0;
}
Edit:
What makes me confused is the behavior in python. The following python code prints a:
arr=[["abcd","efgh","ijkl"],["mnop","qrst","xwyz"]]
print arr[0][0][0]
It addresses to the first letter of the first string in the first list.
I would think that the equivalent of this in c++ would be:
#include <iostream>
using namespace std;
int main()
{
string arr [2] [3] [4]={
{"abcd","efgh","ijkl"},
{"mnop","qrst","xywz"}
};
cout<<arr[0][0][0]<<endl;
return 0;
}
by pointing to the first letter in the first string of the first array. But this prints the first string abcd. My question is why should i put another [0] in order to get to the a?
Your initializer populates the array as follows:
arr[0][0][0] = "abcd";
arr[0][0][1] = "efgh";
arr[0][0][2] = "ijkl";
arr[1][0][0] = "mnop";
arr[1][0][1] = "qrst";
arr[1][0][2] = "xywz";
All other elements are default-initialized to empty string.
Thus, arr[1][0][1] is the string containing "qrst", and arr[1][0][1][1] is the second character of that string, namely 'r'.
You've confused the standard library string object with the concept of a c-string/string literal, and you've helped yourself with this by avoiding the use of the std:: prefix. If we add this, it starts to make more sense:
std::string arr [2] [3] [4]={
{"abcd","efgh","ijkl"},
{"mnop","qrst","xywz"}
};
What you are declaring here is an array of 2 x 3 x 4 instances of std::string. But what you wrote looks like you thought you were declaring character arrays:
char arr [2] [3] [4] = {
{"abcd","efgh","ijkl"},
{"mnop","qrst","xywz"}
};
would almost have the effect you were trying to achieve -- in this case arr[0][0][0] does point to a rather than the string.
Unfortunately the problem here is that you've specified a final dimension of 4 and then supplied 5-character c-strings to the initializer. Remember:
"abcd"
is equivalent to
{ 'a', 'b', 'c', 'd', 0 }
because c-strings are nul-terminated. So you would need to write
char arr [2] [3] [5] = {
{"abcd","efgh","ijkl"},
{"mnop","qrst","xywz"}
};
or, if what you actually want is specifically arrays of characters, not nul-terminated c-strings:
charr arr[2][3][4] = {
{ { 'a', 'b', 'c', 'd' }, { 'e', 'f', 'g', 'h' }, ...
std::string is a discrete object, not an alias for a c-string.
#include <iostream>
#include <string>
int main() {
std::string arr[2][3] = {
{ "abcd", "efgh", "ijkl" },
{ "mnop", "qrst", "wxyz" }, // who needs 'u' or 'v'?
};
std::cout << "arr[0][0] = " << arr[0][0] << "\n";
std::cout << "arr[0][0][0] = " << arr[0][0][0] << "\n";
}
http://ideone.com/JQrDxr
The array you initialized is probably not what you wanted to initialize.
One dimension string array
string arr [2]= {"abcd","efgh"};
Two dimensional string array
string arr [2][2]= {{"abcd","efgh"}, {"ijkl","mnop"}};
Three dimensional string array
string arr [2][2][2]= {
{
{"abcd","qwer"},
{"efgh","tyui"}
},
{
{"ijkl","zxcv"},
{"mnop","bnmo"}
}
};
so, cout<<arr [1] [0] [1] [1]<<endl; will output 'x'
You can't compare python to c++ because in python a list and a string is nearly the same while in c++ there completely different. In Python it doesn't matter if you write
arr=[["abcd","efgh","ijkl"],["mnop","qrst","xwyz"]]
or
arr=[["a","b","c","d","e","f","g","h","i","j","k","l"],
["m", "n","o","p","q","r","s","t","x","w","y","z"]]
because there meaning the same. in c++ instead it treats a string as one "container" which leads to your observed behavior that it will assign these "containers" to the first indexes instead the individual chars. What you can instead do is
char[2][12] arr = {
{"a","b","c","d","e","f","g","h","i","j","k","l"},
{"m", "n","o","p","q","r","s","t","x","w","y","z"}
};

Converting letters to numbers in C++

PROBLEM SOLVED: thanks everyone!
I am almost entirely new to C++ so I apologise in advance if the question seems trivial.
I am trying to convert a string of letters to a set of 2 digit numbers where a = 10, b = 11, ..., Y = 34, Z = 35 so that (for example) "abc def" goes to "101112131415". How would I go about doing this? Any help would really be appreciated. Also, I don't mind whether capitalization results in the same number or a different number. Thank you very much in advance. I probably won't need it for a few days but if anyone is feeling particularly nice how would I go about reversing this process? i.e. "101112131415" --> "abcdef" Thanks.
EDIT: This isn't homework, I'm entirely self taught. I have completed this project before in a different language and decided to try C++ to compare the differences and try to learn C++ in the process :)
EDIT: I have roughly what I want, I just need a little bit of help converting this so that it applies to strings, thanks guys.
#include <iostream>
#include <sstream>
#include <string>
int returnVal (char x)
{
return (int) x - 87;
}
int main()
{
char x = 'g';
std::cout << returnVal(x);
}
A portable method is to use a table lookup:
const unsigned int letter_to_value[] =
{10, 11, 12, /*...*/, 35};
// ...
letter = toupper(letter);
const unsigned int index = letter - 'A';
value = letter_to_value[index];
cout << index;
Each character has it's ASCII values. Try converting your characters into ASCII and then manipulate the difference.
Example:
int x = 'a';
cout << x;
will print 97; and
int x = 'a';
cout << x - 87;
will print 10.
Hence, you could write a function like this:
int returnVal(char x)
{
return (int)x - 87;
}
to get the required output.
And your main program could look like:
int main()
{
string s = "abcdef"
for (unsigned int i = 0; i < s.length(); i++)
{
cout << returnVal(s[i]);
}
return 0;
}
This is a simple way to do it, if not messy.
map<char, int> vals; // maps a character to an integer
int g = 1; // if a needs to be 10 then set g = 10
string alphabet = "abcdefghijklmnopqrstuvwxyz";
for(char c : alphabet) { // kooky krazy for loop
vals[c] = g;
g++;
}
What Daniel said, try it out for yourself.
As a starting point though, casting:
int i = (int)string[0] + offset;
will get you your number from character, and: stringstream will be useful too.
How would I go about doing this?
By trying to do something first, and looking for help only if you feel you cannot advance.
That being said, the most obvious solution that comes to mind is based on the fact that characters (i.e. 'a', 'G') are really numbers. Suppose you have the following:
char c = 'a';
You can get the number associated with c by doing:
int n = static_cast<int>(c);
Then, add some offset to 'n':
n += 10;
...and cast it back to a char:
c = static_cast<char>(n);
Note: The above assumes that characters are consecutive, i.e. the number corresponding to 'a' is equal to the one corresponding to 'z' minus the amount of letters between the two. This usually holds, though.
This can work
int Number = 123; // number to be converted to a string
string Result; // string which will contain the result
ostringstream convert; // stream used for the conversion
convert << Number; // insert the textual representation of 'Number' in the characters in the stream
Result = convert.str(); // set 'Result' to the contents of the stream
you should add this headers
#include <sstream>
#include <string>
Many answers will tell you that characters are encoded in ASCII and that you can convert a letter to an index by subtracting 'a'.
This is not proper C++. It is acceptable when your program requirements include a specification that ASCII is in use. However, the C++ standard alone does not require this. There are C++ implementations with other character sets.
In the absence of knowledge that ASCII is in use, you can use translation tables:
#include <limits.h>
// Define a table to translate from characters to desired codes:
static unsigned int Translate[UCHAR_MAX] =
{
['a'] = 10,
['b'] = 11,
…
};
Then you may translate characters to numbers by looking them up in the table:
unsigned char x = something;
int result = Translate[x];
Once you have the translation, you could print it as two digits using printf("%02d", result);.
Translating in the other direction requires reading two characters, converting them to a number (interpreting them as decimal), and performing a similar translation. You might have a different translation table set up for this reverse translation.
Just do this !
(s[i] - 'A' + 1)
Basically we are converting a char to number by subtracting it by A and then adding 1 to match the number and letters