понедељак, 12. децембар 2011.

C++ Win32 API Tutorial


C++ Win32 API Tutorial

 
You may have already done quite a bit of console programming with C++. Although, you probably wondered how they get those nice graphical user interfaces (GUI) in windows programs that don't have a black screen. Well, these GUI programs are called Win32 API programs. Learn how to make buttons, windows, text edits, and other GUI objects in Windows 32 programming.
They use the windows 32-bit Application programming interface, which basically means interacting with Windows operating systems such as Windows XP or Vista. In this tutorial, you will learn how to use C++ with the Win32 APIto make wonderful Windows Applications.
Windows programs register themselves on the operating system and work with one loop for messages. In addition, the message loop goes through a process function that handles all the windows messages and delivers what the user or operating system demands.
The most common windows messages are WM_CREATEWM_DESTROY, and WM_COMMAND. WM Stands forWindows Message. CREATE handles the initial message that the program receives upon registering itself with the windows operating system''s process list. You can add most of your GUI code inside WM_CREATE, and any other code that initializes the program. WM_DESTROY would be for any variables you need to delete or GUI you need to clean up to avoid memory leaks; it is also used for saving last minute settings, like the state of the program was left last. WM_COMMAND is basically your event handler, and you handle all sorts of messages for your buttons or GUI, and messages from other programs or any other user input.
Our first example will create a window with one button that will pop up a message box when clicked.
#include <windows.h>

/*  Declare Windows procedure  */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);

Ok, first we included our windows.h, this is the main header that links the Win32 API with your program.
We then declare a prototype WindowProcedure function defined as an LRESULT CALLBACK, which is just a windows data type for certain functions. A prototype is a function that is defined at the top but will be declared later on in the program, so you will see this same function again but with actual code later. We declare the arguments for this function as HWND, UINT, WPARAM, and LPARAM.
HWNDs are usually used for GUI elements; they represent the actual window or window elements of a program. UINT is an unsigned integer and WPARAM and LPARAM are parameter messages that windows uses to add more data into a message.
#define IDBUTTON 102

/*  Make the class name into a global variable  */
char szClassName[ ] = "MyFirstProgram";
HINSTANCE g_hInst;

It is important to declare your globals and definitions at the top of your program. IDBUTTON is our id defined as 102, which is a standard definition for a GUI control ID. We will use this definition to link our button to handle what happens in the event that the button is clicked. HINSTANCE is the program's instance; it is used to define what program a GUI belongs to. We declared it globally because we are going to use it throughout the program. szClassName is the class name that the Windows Operating system requires us to register the program with.

WINAPI WinMain Function

int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nFunsterStil) {
    HWND hwnd;               /* This is the handle for our window */
    MSG messages;            /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */

    /* The Window structure */
    g_hInst = hThisInstance;
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows''s default color as the background of the window */
    wincl.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;
We define our WinMain program, which is a special function that windows OS recognizes. We declare the HWND of our main program, which is the main window of the program. We then declare the MSG of our program that we will use to create our Windows message loop. In addition, we create the object of WNDCASSEX which is the structure used to register some data about our program in Windows OS.

Message Event Loop For Windows

After we define our data, we register our class and check for any errors.
    /* The class is registered, let''s create the program*/
    hwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "MyFirstProgram v1.0.0.0",       /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           230,                 /* The programs width */
           75,                  /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

    /* Make the window visible on the screen */
    ShowWindow (hwnd, SW_SHOW);
    UpdateWindow(hwnd);

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while (GetMessage (&messages, NULL00))
    {
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }
    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}
We use CreateWindowEx to build our main window GUI. We define some information about what kind of window we are creating.
We then show the window, update it, and begin our message loop so that our program can actually communicate with the operating system.

Windows Procedure Callback

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){
    HWND hwndButton;
    switch (message) {                 /* Handles all Windows Messages */
        case WM_COMMAND:{
              if(((HWND)lParam) && (HIWORD(wParam) == BN_CLICKED)){
                int iMID;
                iMID = LOWORD(wParam);
                switch(iMID){
                  case IDBUTTON:{
                       MessageBox(hwnd, (LPCTSTR)"You just pushed me!",  (LPCTSTR) "My Program!", MB_OK|MB_ICONEXCLAMATION);
                       break;
                       }
                  default:
                       break;
                }
              }
              break;
            }
        case WM_DESTROY:{
              PostQuitMessage (0);       /* send a WM_QUIT to Message Queue, to shut off program */
              break;
             }
The Window Procedure function is the Win32 API way of sending and receiving Windows messages declared as WM_ .
We define the actual function that we prototyped earlier in the program. We create an HWND for the button, and declare each of our window messages and process them.
In WM_COMMAND, we use a switch to look at the LPARAM and WPARAM parameters, and decide what command has been sent to us and about which control. If we receive the correct message that states our button was clicked, we show a message box.
In WM_DESTROY, we declare PostQuitMessage(0), to exit our program. This message is activated when the X button is clicked on our title bar.

Window Message Create

        case WM_CREATE:{
               hwndButton = CreateWindowEx(0,                    /* more or ''extended'' styles */
                         TEXT("BUTTON"),                         /* GUI ''class'' to create */
                         TEXT("Push Me"),                        /* GUI caption */
                         WS_CHILD|WS_VISIBLE|BS_DEFPUSHBUTTON,   /* control styles separated by | */
                         10,                                     /* LEFT POSITION (Position from left) */
                         10,                                     /* TOP POSITION  (Position from Top) */
                         200,                                    /* WIDTH OF CONTROL */
                         30,                                     /* HEIGHT OF CONTROL */
                         hwnd,                                   /* Parent window handle */
                         (HMENU)IDBUTTON,                        /* control''s ID for WM_COMMAND */
                         g_hInst,                                /* application instance */
                         NULL);
               break;
             }
        default:                      /* messages that we will not process */
            return DefWindowProc (hwnd, message, wParam, lParam);
    }

    return 0;
}
In WM_CREATE we use CreateWindowEx to create a graphical control as a button. We define the text we use, the styles, the positions, the sizes, the parent window, our menu ID which we use in WM_COMMAND, and declare which HINSTANCE this control belongs to.
Default is called when a message comes that we do not want to handle. Of course at the end of our program we return 0, since we declared the function as an int, and windows waits for us to return a zero.
Some C++ and Win32 Data types

DataTypes

You do not need to know the following datatypes in order to use Win32 API, the lesson here is, that most Win32 datatypes are similar, if not the same as C++ datatypes. You are free to use standard C++ datatypes to express any Win32 datatypes. A lot of the datatypes in Win32 API, are synonyms and are not really that important to know, but I''ll give you a quick reference anyway:
-BOOL is a windows datatype that is an equal representation of the simple bool used in C++. Its value can either be true or false.
-WORD This is a 16-bit integer, that is similar to long. Specifically used for some windows functions. It is the equivalent of unsigned short in C++.
-FLOAT is the equivalent of float in C++.
-UINT is the equivalent of unsigned int in C++.
-WINAPI, APIENTRY, CALLBACK, APIPRIVATE, STDCALL are all exactly the same as __stdcall in C++, which is the standard calling convention.
-CDECL, WINAPIV, are both the same as __cdecl calling convention in C++.
-FASTCALL is the same as __fastcall calling convention in C++.
-PASCAL is the same as __pascal calling convention in C++.
-WPARAM equivalent to an unsigned int pointer, and is used in Windows Messages.
-LPARAM in Win32 API this is used for Windows Messages, starting with prefix WM_, but is actually a pointer to along.
-LRESULT Same as HRESULT or LONG/long, but a pointer to the long.
-INT Standard integer datatype, same as int in C++ (signed).
-BYTE is a synonym for unsigned char in C++. It is used for text characters.
-DWORD This is similar to LONG or long in standard C++.
-LONG is a substitute for INT.
-HRESULT is the exact equivalent of a long in C++.
-HANDLE This is a standard long in Win32 API, but usually used to indicate a GUI object, graphical object, or some other win32 objects.
-HINSTANCE This is also a long similar to HANDLE except used to declare the instance of a windows program. Similar to a window ID for each object in win32.
-HWND This long is used to indicate the window object itself, hence the name H-Wind(ow).
-LPSTR Pointer to a string in Win32.
-LPCSTR This object is a long pointer to a constant string.
-LPTSTR This long pointer is equivalent to LPSTR, but there are two versions of this function, one expecting an ANSI string, and the other expecting a Unicode string.
-LPCTSTR This is a combination of TCHARs in an LPTSTR. It can contain unicode or ANSI.

Learning Win32 API C++ Programming

Of course there are many more Window Messages that you could handle, and many more CreateWindowEx classes that we can use in our program, including many other GUI functions that we can show instead of a message box. For further reading and learning about more messages I ask that you favorite this tutorial andhttp://msdn.microsoft.com/library
I tried to make this tutorial as simple as possible to follow for beginners and also enough examples for many of you to understand the structure of a windows program. However, I'm sure that one will have many questions about the various functions and data types.
You may have already done quite a bit of console programming with C++. Although, you probably wondered how they get those nice graphical user interfaces (GUI) in windows programs that don't have a black screen. Well, these GUI programs are called Win32 API programs.

петак, 9. децембар 2011.

UPP


#include <CtrlLib/CtrlLib.h>

using namespace Upp;

#define LAYOUTFILE <Tcc Demo Gui/Tcc Demo Gui.lay>
#include <CtrlCore/lay.h>

class Tcc_Demo : public WithMainLayout<TopWindow> {
public:
    void RunProgram();
    void OpGetExe_Action();

    typedef Tcc_Demo CLASSNAME;
    Tcc_Demo();
};

/* It is always necessary to include Tcc.h */

#include "Tcc/Tcc.h"

/* This function will be called from the Tcc program in memory. */

double plus(double a, double b)
{
   return a + b;
}

/* Program to be run in memory source code. '\n' are not necessary. */

char my_program_in memory[] =

/* If AddIncludePath() is not used TCC will not find probably the #include files */

        "#include <stdio.h>\n"
        "#include <math.h>\n"
        "\n"

/* As with any C source, library functions have to be declared. */

        "double plus(double a, double b);\n"
        "\n"

/*This is the function called from the main program.
As many functions as necessary can be called from the main program. */

        "double pow2(double d)\n"
        "{\n"
        "    return (d*d);\n"
        "}\n"
        "\n"

/*Remember that all static and global variables will be lost between function calls. All durable storage has to be located in the main program.
There is no need for any "main()" function. */

        "double test(double a, char *str)\n"
        "{\n"  
        "    if (a < 0.)\n"
        "        throw(\"Argument is negative!\");\n"  
        "    double ret = 0;\n"
        "    int i;\n"
        "    for (i = 0; i < 10000000; ++i)\n"  
        "        ret += 0.000000001*pow2(sqrt(plus(a, 10)));\n"
        "    snprintf(str, 1024, \"The result is %f\", ret);\n"
        "    return ret;\n"
        "}";

/* Program to be copied to an executable file source code */

char my_program_in_file[] =
        "#include <stdio.h>\n"
        "\n"
        "int fib(n)\n"
        "{\n"
        "    if (n <= 2)\n"
        "        return 1;\n"
        "    else\n"
        "        return fib(n-1) + fib(n-2);\n"
        "}\n"
        "\n"
        "int main(int argc, char **argv)\n"
        "{\n"
        "    int n = 30;\n"
        "\n"
        "    printf(\"\\nCompute nth Fibonacci number fib(%d) = \", n);\n"
        "    printf(\"%d\", fib(n));\n"
        "\n"
        "    printf(\"\\nPress a key to end\");\n"
        "    getchar();\n"
        "    return 0;\n"
        "}";

void Tcc_Demo::RunProgram()
{
    try {

/* In Windows. .dll has been copied to windows/system folder. If not it has to be defined in the Tcc constructor. */

        Tcc tcc;
   
/* Here it is defined what to do with the compiled program */

        if (OpGetExe)
            tcc.SetOutputExe();
        else
            tcc.SetOutputMemory();


/* Set here the include and library directories located in Tcc/lib/include and Tcc/lib/lib */

        tcc.AddIncludePath(EditIncludePath.GetData().ToString());
        tcc.AddLibraryPath(EditLibsPath.GetData().ToString());
   
/* This order has to be followed:
1. Compile source C script */

        tcc.Compile(SourceCode.GetData().ToString());

/* 2.1 If compiled and run in memory */

        if (!OpGetExe) {

/* 2.1.1 Add all functions in the main program that can be called from the C script.
As many functions as necessary can be called from the main program.
Remember to declare them in the C script */

            tcc.AddSymbol("plus", (void *)&plus);

/* 2.1.2 Link the C script to the main program functions */

            tcc.Link();

/* 2.1.3 Get the addresses of all C Script functions to be called from the main program */

            double (*mytest1)(double, char *) = (double (*)(double, char *))tcc.GetSymbol("test");
       
            char str[1024];

/* 2.1.4 Call the C script functions */

            double res = mytest1(90, str);
            PromptOK("The result for Test is " + FormatDouble(res) + ". " + str);

/* 2.2 If compiled to an executable file */

        } else {

/* 2.2.2 Link the C script to the executable file */

            tcc.Link(EditExeFile.GetData().ToString());
            PromptOK("Program compiled in " + DeQtf(EditExeFile.GetData().ToString()));
        }
    } catch(Exc err){

/* 3. Catch the compiling, linking and running (if run in memory) errors. */

        Exclamation(DeQtfLf(err));
    }
}

void Tcc_Demo::OpGetExe_Action()
{
    switch (OpGetExe) {
        case 0:
            EditExeFile.Enable(false);
            SourceCode.SetData(my_program_in_memory);
            break;
        default:
            EditExeFile.Enable(true);
            SourceCode.SetData(my_program_in_file);
    }
}

Tcc_Demo::Tcc_Demo()
{
    CtrlLayout(*this, "Tcc Demo");
    ButRun.WhenPush = THISBACK(RunProgram);
    OpGetExe.WhenAction = THISBACK(OpGetExe_Action);
    OpGetExe = 0;
    OpGetExe_Action();
#if defined(PLATFORM_WIN32)
    EditExeFile.SetData(AppendFileName(GetHomeDirectory(), "tccdemo.exe"));
#else
    EditExeFile.SetData(AppendFileName(GetHomeDirectory(), "tccdemo"));
#endif
    EditIncludePath <<= "/mnt/C/Desarrollo/Aplicaciones/zlibs/Tcc/lib/include";//"...put here right path.../Tcc/lib/include";      
    EditLibsPath <<= "/mnt/C/Desarrollo/Aplicaciones/zlibs/Tcc/lib/lib";//"...put here right path.../Tcc/lib/lib";
    SourceCode.SetFont(Courier(12));
    Sizeable();
}

GUI_APP_MAIN
{
    Tcc_Demo().Run();
}

четвртак, 8. децембар 2011.

Input output c


C Programming

  
Handling User Input In C
scanf() has problems, in that if a user is expected to type an integer, and types a string instead, often the program bombs. This can be overcome by reading all input as a string (use getchar()), and thenconverting the string to the correct data type.

/* example one, to read a word at a time */
#include <stdio.h>
#include <ctype.h>
#define MAXBUFFERSIZE   80

void cleartoendofline( void );  /* ANSI function prototype */

void cleartoendofline( void )
{
 char ch;
 ch = getchar();
 while( ch != '\n' )
  ch = getchar();
}

main()
{
 char    ch;                     /* handles user input */
 char    buffer[MAXBUFFERSIZE];  /* sufficient to handle one line */
 int     char_count;             /* number of characters read for this line */
 int     exit_flag = 0;
 int     valid_choice;

 while( exit_flag  == 0 ) {
  printf("Enter a line of text (<80 chars)\n");
  ch = getchar();
  char_count = 0;
  while( (ch != '\n')  &&  (char_count < MAXBUFFERSIZE)) {
   buffer[char_count++] = ch;
   ch = getchar();
  }
  buffer[char_count] = 0x00;      /* null terminate buffer */
  printf("\nThe line you entered was:\n");
  printf("%s\n", buffer);

  valid_choice = 0;
  while( valid_choice == 0 ) {
   printf("Continue (Y/N)?\n");
   scanf(" %c", &ch );
   ch = toupper( ch );
   if((ch == 'Y') || (ch == 'N') )
    valid_choice = 1;
   else
    printf("\007Error: Invalid choice\n");
   cleartoendofline();
  }
  if( ch == 'N' ) exit_flag = 1;
 }
}

Another Example, read a number as a string

/* example two, reading a number as a string */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define MAXBUFFERSIZE   80

void cleartoendofline( void );          /* ANSI function prototype */

void cleartoendofline( void )
{
 char ch;
 ch = getchar();
 while( ch != '\n' )
  ch = getchar();
}

main()
{
 char    ch;                     /* handles user input */
 char    buffer[MAXBUFFERSIZE];  /* sufficient to handle one line */
 int     char_count;             /* number of characters read for this line */
 int     exit_flag = 0, number, valid_choice;

 while( exit_flag  == 0 ) {
  valid_choice = 0;
  while( valid_choice == 0 ) {
   printf("Enter a number between 1 and 1000\n");
   ch = getchar();
   char_count = 0;
   while( (ch != '\n')  &&  (char_count < MAXBUFFERSIZE)) {
    buffer[char_count++] = ch;
    ch = getchar();
   }
   buffer[char_count] = 0x00;      /* null terminate buffer */
   number = atoi( buffer );
   if( (number < 1) || (number > 1000) )
    printf("\007Error. Number outside range 1-1000\n");
   else
    valid_choice = 1;
  }
  printf("\nThe number you entered was:\n");
  printf("%d\n", number);

  valid_choice = 0;
  while( valid_choice == 0 ) {
   printf("Continue (Y/N)?\n");
   scanf(" %c", &ch );
   ch = toupper( ch );
   if((ch == 'Y') || (ch == 'N') )
    valid_choice = 1;
   else
    printf("\007Error: Invalid choice\n");
   cleartoendofline();
  }
  if( ch == 'N' ) exit_flag = 1;
 }
}


©Copyright B Brown. 1984-1999. All rights reserved.
  

C++ input output II.



Book Cover

Introduction to Scientific Programming
Computational Problem Solving Using:
Maple and C
Mathematica and C

Author:
Joseph L. Zachary
Online Resources:
Maple/C Version
Mathematica/C Version

Printf/Scanf Tutorial

In this tutorial we will discuss a few of the details involved in using printf and scanf, which are introduced in Chapter 11. You will be using some example programs in this laboratory. You can use your Web browser to view them or download them as you prefer.

Output with printf

The program printfdemo.c illustrates some of the behavior of printf. Take a look at it, and then compile and run it. You should notice:
  • To print a character string, supply the string (contained in double quotes) as the parameter to printf. This string is called the format string. The two-character sequence \n displays a newline, and the two-character sequence \t displays a tab.
  • To print an int, embed the sequence %d in the format string, and include an integer expression as a second parameter. (The sequence %d is called a conversion specification.) The value of the expression will be displayed in place of the %d.
  • To print a double, embed one of the sequences %g%f, or %e in the format string, and include a floating-point expression as a second parameter. The value of the expression will be displayed in place of the conversion specification. The way that the value will be displayed depends upon which of the three conversion specifications you use.


    • The %g specification displays the number as a six-digit mantissa, with an exponent if necessary.
    • The %f specification displays the number with six digits after the decimal point and no exponent.
    • The %e specification displays the number using scientific notation, with one digit before the decimal point, six after the decimal point, and an exponent.

  • To display more than one number, include more than one conversion specification and more than one extra parameter.

Type Correspondence

It is crucial that the type of the value being displayed match up with the conversion specification. If it doesn't, garbage will be displayed. Modify the calls to printf so that n is used in place of x and x is used in place of n and you'll see what we mean.

Floating-Point Conversion Specifications

Modify printfdemo.c back to its original form. To get a better appreciation for the differences among the three conversion specifications for floating-point numbers, try changing the value of x so that it is extremely large (123456789e30), extremely small (123456789e-30), and moderate (123456.789).
The most generally useful of the floating-point conversion specifications is %g. We suggest that you always use it unless you have a good reason not to.

Conversion Options

Modify printfdemo.c back to its original form (the value of x should be .00000123456789).
It is possible to use more complicated conversion specifications to fine-tune the appearance of the numbers displayed by printf. There are a large number of options, but we will focus on controlling theprecision to which floating-point numbers are displayed.
You can ask for 3 digits of precision, for example, by using one of %.3g%.3f, or %.3e. Change each of the floating-point conversion specifications in printfdemo.c so that it asks for 3 digits of precision, then compile and run the program.
If you don't specify otherwise, the precision defaults to 6. When the precision is p:
  • the %g specification results in a p-digit mantissa,
  • the %f specification results in p digits after the decimal point, and
  • the %e specification results in p digits after the decimal point.
Try out the modified program with extremely large (123456789e30), extremely small (123456789e-30), and moderate (123456.789).
Try setting the precision to 30 and see what happens. Even though doubles only have 15 digits of mantissa, C obligingly displays plenty of garbage digits.

Input with scanf

The program scanfdemo.c in your examples directory illustrates the behavior of scanf. Take a lot at it, and then compile and run it. You should notice
  • To read an int, supply scanf with a format string containing the conversion specification %d, and include an int variable preceded by an ampersand (&) as the second parameter.
  • To read a double, supply scanf with a format string containing the conversion specification %lf (that's a lower case L, not a one), and include a double variable preceded by an ampersand as the second parameter.
  • To read more than one number, include more than one conversion specification and more than one extra parameter.

Importance of the Ampersand

It is important to put the ampersand in front of the variables that appear as parameters to scanf, and it is easy to forget to do this. Remove the ampersand and compile and run the program. The program will crash before it runs to completion. Put the ampersand back. If you see this behavior in the future, check your scanf statements.

Type Correspondence

As with printf, it is important that the type of the variable being read match up with the conversion specification. Try changing the conversion specification in the first call to scanf to %lf. After compiling and running the program, change it back.

How scanf Consumes Input

When scanf is called, it skips over all leading white space (spaces, tabs, and newlines). Try recompiling and running scanfdemo. Each time it prompts for a number, try entering a bunch of newlines, spaces, and tabs before typing the number. The extra white space will have no effect.
After scanf has skipped over white space, it reads until it finds something that doesn't belong in the type of number than it is looking for and then quits. It leaves any remaining input behind for the next call toscanf. Run scanfdemo, and when it prompts for the first number enter
1.2 3.4
You will see than scanf reads the 1 as an integer, stopping when it encounters the decimal point (which can't be part of an integer). It later reads the .2 as a double, stopping when it encounters the white space. Then it reads the 3 as an integer, and the .4 as a double. Notice that if there is input left over from a previous call, scanf will use it.
Now run the program and enter
x
None of the calls to scanf can get past the x, so the uninitialized values of the variables are displayed.
Be careful when you supply input to your programs that you only type in properly formatted numbers and white space. While it is possible to write programs that are more robust in the face of bad input, we will not be going into that topic.


C++ input output


CHAPTER 7: Input and Output
Input and output facilities are not part of the C language itself, so we have not emphasized them in our presentation thus far. Nonetheless, programs interact with their environment in much more complicated ways than those we have shown before. In this chapter we will describe the standard library, a set ,)f functions that provide input and output, string handling, storage manage­ment, mathematical routines, and a variety of other services for C programs. We will concentrate on input and output.
The ANSI standard defines these library functions precisely, so that they can exist in compatible form on any system where C exists. Programs that confine their system interactions to facilities provided by the standard library can be moved from one system to another without change.
The properties of library functions are specified in more than a dozen headers; we have already seen several of these, including <stdio.h>, <string.h>, and <ctype.h>. We will not present the entire library here, since we are more interested in writing C programs that use it. The library is described in detail in Appendix B.
7.1 Standard Input and Output
As we said in Chapter 1, the library implements a simple model of text input and output. A text stream consists of a sequence of lines; each line ends with a newline character. If the system doesn’'t operate that way, the library does. whatever is necessary to make it appear as if it does. For instance, the library might convert carriage return and linefeed to newline on input and back again on output.
The simplest input mechanism is to read one character at a time from the standard input, normally the keyboard, with getchar:
int getchar(void)
getchar returns the next input character each time it is called, or EOF when it encounters end of' file. The symbolic constant EOF is defined in <stdio.h>.  The value is typically -1, but tests should be written in terms of EOF so as to be independent of the specific value.
In many environments, a file may be substituted for the keyboard by using the < convention for input redirection: if a program prog uses getchar, then the command line
prog <infile
causes prog to read characters from infile instead. The switching of the input is done in such a way that prog itself is oblivious to the change; in particular, the string "<infile" is not included in the command-line arguments in argv. Input switching is also invisible if the input comes from another program via a pipe mechanism: on some systems, the command line
otherprog | prog
runs the two programs otherprog and prog, and pipes the standard output of otherprog into the standard input for prog. The function
int putchar(int)
is used for output: putchar (c) puts the character c on the standard output, which is by default the screen. putchar returns the character written, or EOF if an error occurs. Again, output can usually be directed to a file with >filename: if prog uses putchar,
prog >outfile
will write the standard output to outfile instead.
If pipes are supported,
 prog | anotherprog
puts the. standard output of prog into the standard input of anotherprog.
Output produced by printf also finds its way to the standard output. Calls to putchar and printf may be interleaved—output appears in the order in which the calls were made.
Each source file that refers to an input/output library function must contain the line
#include <stdio.h>
before the first reference. When the name is bracketed by < and > a search is made for the header in a standard set of places (for example, on UNIX system,. typically in the directory /usr/include).
Many programs read only one input stream and write only one output stream; for such programs, input and output with getchar, putchar, and printf may be entirely adequate, and is certainly enough to get started. This is particularly true if redirection is used to connect the output of one program to the input of the next.
For example, consider the program lower, which converts its input to lower case:
#include <stdio.h>
#include <ctype.h>
main() /* lower: convert input to lower case */ {
int c;
while ((c = getchar()) 1= EOF) putchar(tolower(c)); return 0;
The function tolower is defined in <ctype.h>; it converts an upper case letter to lower case, and returns other characters untouched.  Regardless of how the <ctype.h> functions are implemented on a given machine, programs that use them are shielded from knowledge of the character set.
7.2   Formatted Output—Printf
The output function printf translates internal values to characters. We have used printf informally in previous chapters. The description here covers the typical uses but is not complete; for the full story, see Appendix B.
int printf( char *format, arg, , arg1 , ... )
printf converts, formats, and prints its arguments on the standard output under control of the formatIt returns the number of characters printed.
The format string contains two types of objects: ordinary characters, which are copied to the output stream, and conversion specifications, each of which can ,us conversion and printing of the next successive argument to printfEach conversion specification begins with a % and ends with a conversion character.  Between the % and the conversion character there may be, in order:
·  A minus sign, which specifies left adjustment of the converted argument.
·  A number that specifies the minimum field width. The converted argument will be hinted in a field at least this wide. If necessary it will be padded on the left (or right, if left adjustment is called for) to make up the field width.
·  A period, which separates the field width from the precision.
·  A number, the precision, that specifies the maximum number of characters to be printed from a string, or the number of digits after the decimal point of floating-point value, or the minimum number of digits for an integer.
·  • An h if the integer is to be printed as a short:, or l (letter ell) if as a long
·  Conversion characters are shown in Table 7-I. If the character after the % is not a conversion specification, the behavior is undefined.


Table 7-l. Basic Printf Conversions

CHARACTER
ARGUMENT TYPE;
PRINTED AS
d.i
int;
decimal number.
o
int;
unsigned octal number (without a leading zero).
x,X
int;
unsigned hexadecimal number (without a leading 0x 0X), using abcdef or ABCDEF for 10, ..., 15.
u
int;
unsigned decimal number.
c
int; .
single character
s
char *;
print characters from the string until a '\0' or the number of characters given by the precision.
f
double;
[-]m.dddddd, where the number of d's is given by the precision (default 6).
e,E
double;
[-]m.dddddde±xx or [-]m.ddddddE±xx,where the number of d'is given by the precision (default 6).
g,G
double;
use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use%f. Trailing zeros and a trailing decimal point are not printed.
p
void *;
pointer (implementation-dependent representation). 
%
no argument isconverted;
print a %.

A width or precision may be specified as *, in which case the value is computed by converting the next argument (which must be an int). For example to print at most max characters from a string s,
printf("%.*s", max, s);
Most of the format conversions have been illustrated in earlier chapters.  One exception is precision as it relates to strings. The following table shows the effect of a variety of specifications in printing “hellos, world” (12 characters).  We have put colons around each field so you can see its extent.

:%s:          :hello, world:
:%10s:        :hello, world:
:%.10s:      :hello, wor:
:%-10s:      :hello, world:
:%.15s:      :hello, world:
:%-15s:      :hello, world    ;
:%15.10s;    ;     hello, wor:
:%-15.10s:  :hello, wor      ;
A warning: printf uses its first argument to decide how many arguments follow, and what their types are;  it will get confused, and give wrong answers, if there are not enough arguments, or if they are of the wrong types.  You should also be aware of the difference between these two calls:

printf(s);
/* FAILS if s contains a % */
printf(“%s”,s);
/* Safe */

7.4 Formatted Input—Scant
The function scanf is the input analog of printf, providing many of the me conversion facilities in the opposite direction.
int scanf(char *format, ...)
scanf reads characters from the standard input, interprets them according to the specifications in format, and stores the results through the remaining arguments. The format argument is described below; the other arguments, each of which must be a pointer, indicate where the corresponding converted input should be stored. As with printf, this section is a summary of the most useful features, not an exhaustive list.
scanf stops when it exhausts its format string, or when some input fails to match the control specification. It returns as its value the number of successfully matched and assigned input items. This can be used to decide how many items were found. On end of file, EOF is returned; note that this is different ' from 0, which means that the next input character does not match the first specification in the format string. The next call toscanf resumes searching immediately after the last character already converted.
There is also a function sscanf that reads from a string instead of the :standard input:
int sscanf (char *string, char *format, arg1, arg2,... )
It scans the string according to the format in format, and stores the resulting values through arg1, arg2etc. These arguments must be pointers.  The format string usually contains conversion specifications, which are used to control conversion of input. The format string may contain:
·  Blanks or tabs, which are ignored.
·  Ordinary characters (not %), which are expected to match the next non-white space character of the input stream.
·  Conversion specifications, consisting of the character %, an optional assignment suppression character *, an optional number specifying a maximum field width, an optional h, 1, or L indicating the width of the target, and a conversion character.

A conversion specification directs the conversion of the next input field. Normally the result is placed in the variable pointed to by the corresponding argument. If assignment suppression is indicated by the * character, however, the input field is skipped; no assignment is made. An input field is defined as a string of non-white space characters; it extends either to the next white space character or until the field width, if specified, is exhausted. This implies that scanf will read across line boundaries to find its input, since newlines are white space. (White space characters are blank, tab, newline, carriage return, vertical tab, and formfeed.)
The conversion character indicates the interpretation of the input field. The corresponding argument must be a pointer, as required by the call-by-value semantics of C.

Table 7-2. Basic Scanf Conversions

CHARACTER
Input Format
Type
d
decimal integer.
int *
i
integer (may be in octal (leading 0), or hexadecimal (leading 0x or 0X)
int *
o
octal integer (with or without a leading zero).
int *
x
hexadecimal integer (without a leading 0x 0X)
int *
u
unsigned decimal integer.
unsigned int *
c
characters.  The next input characters (default 1) are placed at the indicated spot in memory.
char *
s
character string ( not quoted)
char * pointing to an array of characters large enough to hold all the characters read, plus a n added \0
e,f,g
Floating point number with optional sign, optional decimal point, and optional exponent
float *
%
no argument is converted;
print a %.

The conversion characters d, i, o, u, and x may be preceded by h to indicate that a pointer to short rather than int appears in the argument list, or by 1 (letter ell) to indicate that a pointer to long appears in the argument list... Similarly, the conversion characters e, f, and g may be preceded by l to indicate that a pointer to double rather than float is in the argument list.