SWITCH() ....CASE and putch() problem.

(i run windows 32bit, code::blocks IDE as is,i use the default compiler that my IDE has)

For both questions 1) and 2) i fail to understand what is going on. I do not expected to see 97 only a , (only here i wanted 97 to be seen: 'you typed: 97' nowhere else). Can someone help me to understand better the mechanism? What it does? Why i see 97 and why 'a' is <<travelling>>. :-(


1) I get unwanted results for case 'a' in my command window.I see this:

enter char: ( to test the program i typed the character a)
you typed: 97

aaaaaaa ---
a97. <-------Here is my problem.
I expected to see only a. The putch(i) command should give me only character a.

(i know what i did, i did it on purpose: i want to use 'int i;' not 'char i;' so that 'i=getch();' the character i type will convert to an integer and saved inside my 'i' variable.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#include <iostream>
#include <stdlib.h>
#include <conio.h>

using namespace std;

 int main(int argc, char *argv[])
{
    int i;
    cout << "enter char :";
    i=getch();
    cout << endl;
    switch(i)
    {
        case 'a':
            cout << "\naaaaaaa --- \n";
            cout << putch(i); break;
        default:
            cout << "\n444444\n";
    }
    putch('\n');
    system("pause");
}


============================================================================
2) If i change the code a little bit inside the case 'a' :
1
2
3

cout << "\naaaaaaa --- \n" << putch(i); break;


Now i get this unusual result(!):

enter char: ( to test the program i typed the character a)
you typed: 97

a
aaaaaaa ---
97

Now 'a' has travelled to a different position! :-(


I know from what i have read so far that this is what putch(i) should do: show me the character that is saved in the variable i. I know that inside my computer 'char' data types are saved as integer numbers....

(when i type this : char i='a'; I know that inside my computer 'a' will be saved in a memory address i(whatever is the hex number for that i) silently as an integer int data type, which is the ASCII ID 97. 'a' has ASCII ID 97.
Last edited on
<stdlib.h> and <conio.h> are deprecated. I recommend you to use C++ io manipulators instead Windows. Choose one and make an entire program this way ^^.
So is what you want a program, that shows the int representation/ASCII code of each char?
dear bugbyte,

The purpose of this thread is these questions:
"Can someone help me to understand better the mechanism? What it does? Why i see 97 and why 'a' is <<travelling>>. "

nothing else. ty.
Try this (I'm with no computer):
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <conio.h>
int main()
{
    std::cout << "Input a char.: ";
    char i = getch();
    std::cout << ((i == 'a')? ("A: "):("(Try A next time:)" )) << ((int)i);
    return 0;
}


This may do it.
Last edited on
Topic archived. No new replies allowed.