Wednesday, April 2, 2008

char woes and the blight of the console menu

Sometimes, no matter how hard I think about it, or try to avoid thinking about it, my brain finally opens up to a concept that has seemed foreign for so long. Today, while trying to do some other stupid thing with chars in C++ I finally figured out, I mean figured out as in now I understand, the "cannot convert from 'const char' to 'char'" error and I have to say I have egg on my face. But before I get to that, I want to bring up the context that is usually an introduction to programming where errors like this drive noobs batty.

It seems that many programming learning materials, or courses for that matter, tend to introduce the language by having the user make inane, 1970 text menus for some stupid functions, such as inputting names and dates into a database, or doing simple math. These archaic menus require input from the user (who is also primarily the programmer in this case) and then determine the appropriate action based on the input. The concepts are introduced gradually too: first input a single integer, then maybe multiple line inputs, then a single line input with spaces, on up to words and/or names (aka character strings). Things, like inputting your full name, sounds so easy yet causes so much headache. Let me just say I hate this sort of menu making/programming/thinking. It's not what programming is about. You end up fighting the language and syntax instead of learning the concepts. This is sort of user interface crap that I think clouds programming learning with programming fighting. Perhaps its just me, but that error I mention above, along with numerous others in a similar variety, plagued me as I struggled to get my menus working with char, char*, and/or strings. (Additionally, little to no advice is given into which is a more appropriate variable either.)

Perhaps I have the other concepts and syntax down that this one vague area maddens me. Or perhaps it truly is a hard concept to grasp for the intro programmer.

Regardless, here's some code sample to help show what I learned.

char word[10];

//ERROR, character arrays cannot be set this way
word = "great!";
//SOLUTION, use a function to set the array
strcpy(word, "great!");

//ERROR, this one dealing with the index of the
// character array, where you can actually work directly
word[0] = "g";
//SOLUTION, watch your syntax, ' and " mean something
// different. In this case, it's interpreting the set
// to an array, not an individual character.
word[0] = 'g';

Sometimes it’s the simple things…

Share with your network