Archive

Archive for the ‘C Programming’ Category

Functions for converting strings to upper/lower case

February 17, 2009 3 comments

Use following functions

  1. _strupr
  2. _strlwr
  3. std::transform – does the trick too but hard to understand
/* STRLWR.C: This program uses _strlwr and _strupr to create
 * uppercase and lowercase copies of a mixed-case string.
 */

#include <string .h>
#include <stdio .h>

void main( void )
{
   char str[100] = "The String to End All Strings!";
   printf( "Mixed: %s\n", str );
   printf( "Lower: %s\n", _strlwr( str ));
   printf( "Upper: %s\n", _strupr( str ));
}

// Output
// Mixed: The String to End All Strings!
// Lower: the string to end all strings!
// Upper: THE STRING TO END ALL STRINGS!

How about converting std::string to upper or lower case?

// Convert std::string to upper or lower case
std::string teststr = “Nibu Babu Thomas”;
_strlwr( &teststr[0] );
cout << endl << teststr.c_str() << endl; _strupr( &teststr[0] ); cout << teststr.c_str() << endl;[/sourcecode] How about converting 'CString' to upper or lower case? Fortunately and wisely enough there are member functions called 'MakeLower', 'MakeUpper'. Phew! [sourcecode language='cpp']CString csTest = _T( "Nibu Babu Thomas" ); csTest.MakeUpper();// Now in upper case csTest.MakeLower(); // Now in lower case[/sourcecode]

Advertisements

How to check for keyhit in a windows console application?

February 6, 2009 1 comment

For this purpose we use _kbhit function included in conio.h file. Please note that conio.h is a non-standard header file so can’t say if _kbhit will be available in other libraries. The purpose of  _kbhit is to check whether a key has been hit and so then we can use this function to wait till a key is pressed. To know which key is pressed we can use _getch or _getche functions immediately after a call to _kbhit. _kbhit returns TRUE if a key is pressed else returns FALSE.

Internally _kbhit used PeekConsoleInput windows console API to check whethere is a KEY_EVENT in input queue. If there is one then it returns TRUE. Note that _kbhit peeks on all events from input queue to check whether there is a KEY_EVENT. Note that extended keys are ignored!

Here are some functions to demonstrate the power of _kbhit

  1. ClearInputBuffer – Clears key events from input buffer using _kbhit
  2. Pause – Much like window’s ‘Pause’ command, except for the animation of ellipses.

#include
#include

void ClearInputBuffer()
{
   while( _kbhit() )
   {
      // Read and ignore chars from input buffer resulting in removal from input buffer
      _getch();
   }
}

void Pause( const char* Msg = NULL )
{
   std::cout << ( Msg ? Msg : "Press a key to continue" );    const int EllipsesCount = 3;    const char* MoveBackChars[EllipsesCount] = { "\b", "\b\b", "\b\b\b" };    const char* AllClearText[EllipsesCount] = { " ", "  ", "   " };    const char* Ellipses[EllipsesCount] = { ".", "..", "..." };    int ActiveEllipsesIndex = 0;    while( true )// Animate until a key is pressed    {       std::cout << Ellipses[ActiveEllipsesIndex];       Sleep( 500 );       if( !_kbhit() )       {          std::cout << MoveBackChars[ActiveEllipsesIndex];          std::cout << AllClearText[ActiveEllipsesIndex];          std::cout << MoveBackChars[ActiveEllipsesIndex];       }       else       {          _getch();          break;       }       ActiveEllipsesIndex = (ActiveEllipsesIndex + 1) % EllipsesCount;    } } int main( void ) {    ClearInputBuffer();    Pause();    return 0; }[/sourcecode]

Careful with sscanf and fscanf

August 1, 2008 1 comment

If you are not careful while using sscanf and fscanf, you code could lead to stack corruption errors leading to application crash.

Recently when migrating a project in VC6 to VC8, a similar situation arose, I was getting stack corruption errors…

“Run-Time Check Failure #2 – Stack around the variable ‘ByteVar’ was corrupted.”

So I started looking for usage of “ByteVar” in the code being migrated, so a particular innocent looking piece of code got my attention and looked something like this…

BYTE ByteVar = 0; // Declaration
sscanf( Buffer, "%d", &ByteVar );// Looks innocent right?

But the problem here is with the format specifier used for a BYTE var, it should be %c, but it’s %d i.e. sscanf reads in 4 bytes instead of 1 byte but the address passed in is of a BYTE. 😦

In release this works fine and in debug mode above error pops up. Trouble is how to fix this, it’s dangerous to change %d to %c because sscanf will read in only 1 byte instead of four bytes which will result in invalid data being read into other variables. So the safest option IMO is to change the type of “ByteVar” from BYTE to int.

typedef a fixed length array

July 7, 2008 5 comments

Let’s suppose you wanna create a typedef for a fixed length array, so first thing that you would do is this…

typedef char[100] HundredChars;

This will not work as typedefing an array requires different syntax, here is how we do it…

typedef char HundredChars[100];

To know the size of a dynamically allocated chunk of memory

Choosing between a function and a macro definition

June 26, 2008 2 comments

This is a common and a funny problem. So what is this all about? Let me put it like this…

We have a standard “c” function called _toupper and an equivalent macro is also available called _toupper. So my question is how to call function version of _toupper explicitly, if we write _toupper, macro version  get expanded inline, since preprocessor runs before compiler.

Here is the solution…

#include <ctype .h>

const char upper = _toupper( ch ); // Will invoke macro version
const char upper = (_toupper)(ch); // Will invoke function

Another routine is _fileno, implemented both as a function and as a macro. Apply same trick.

const int ErrFileNo = (_fileno)( stderr );
const int OutFileNo = _fileno( stdout );

Another option is to use #undef to undefine the macro definition.

#include </ctype><ctype .h>
#undef _toupper

A friend of mine was saying that he did encounter such bugs due to such “automagic” macro expansion.

Conditional compilation and conditional inclusion of a resource!

January 31, 2008 Leave a comment

Hope you’ve heard of conditional compilation. Conditional compilation simply means what it says, i.e. compile only when a certain condition is true and it’s only meant for the compiler hence it should only take place during compilation.

We do conditional compilation with help of preprocessor commands. For eg:

void WhoIsNibu()
{
    // 😉
    #ifdef NIBU_IS_A_VERY_GOOD_MVP
         printf( "Nibu is an MVP, Mwhahahaha, Nibu loves Jesus" );
    #else
         printf( "Nibu is still an MVP hehe ;), He loves Jesus" );
    #endif
}

Well now the first printf will only be “compiled” if you define NIBU_IS_A_VERY_GOOD_MVP else the second one will be “compiled”.

Well this was something about conditional compilation, now about including a resource based on a condition. This is mainly for those who are using VC resource editor to include a resource for others you can simply follow normal conditional compilation to decide whether to include or not to include a resource…

In VC resource editor right click on a resource for eg: a menu resource and select properties, now you will find a text field called “Condition”

Condition

See the controls encircled in red.

I’ve entered _DEBUG here, so this menu will only be compiled into the exe when _DEBUG is defined else it won’t be.

Very easy isn’t it. Recently someone asked this in a forum hence thought of posting it here. This is in VC6 but I am sure there is a similar (and better) option in later versions of visual studio too.

%d bloggers like this: