开发者

Problem with character input by getchar() or getche()

When I compile the C codes (from Teach yourself C, 2nd edition-Herbert Schildt) written below in Borland C++ v5.02, I get a warning message as below: "c61.c(7,6): Conversion may lose significant digits"

What's wrong?

#include "stdio.h"

main()
{
 char ch;
 ch = getchar();
 printf(" You typed: %c", ch);

 return 0;
}

Same problem with another example:

#include 开发者_开发知识库"conio.h"
#include "stdio.h"

main()
{
 char ch;

 printf("Enter a character: ");
 ch = getche();
 printf("\nIts ASCII code is %d", ch);

 return 0;
}


getchar() returns an int, so that it can return non-character values like EOF. So when you store the return value in a smaller datatype, like a char, you are potentially losing information.

Schildt's books are commonly considered the worst available for learning C (or C++) and this is a good example of why. You would be well advised to get a better book, such as K&R.


The prototype for getchar is:

int getchar (void);

It returns an int because it needs to return EOF which is not a character.


Expanding on that, the function needs to be able to return any valid character, as well as being able to return a special "character" indicating that you're reached the end of file (or an error has occurred).

Since a char data type can only hold one of the characters, there would be no way to indicate this end of file if all the function returned was a char. That's because, if you selected one of those char values to represent end of file, you would not be able to tell the difference between the end of file and the actual character.

For example, let's choose 'A' to indicate end of file. When you actually get back an 'A' from getchar(), how will you know whether you've reached the end of file or whether the user actually entered 'A'?

To get around this, many functions that give you back a char will actually give you an int and use one of the integer values which don't have an actual char equivalent (such as -1).

In that case (assuming an 8-bit char), you would get back either a -1 if you've reached the end of the file or a value from 0 through 255 inclusive representing the character entered.


And you need to get yourself both a more modern book and a more modern compiler:

#include <stdio.h>
int main (void) {
    int ch = getchar();
    if (ch != EOF)
        printf("You typed: %c\n", ch);
    return 0;
}

Why anyone is still using Borland is this day and age (where gcc is both just as cheap and much better) is beyond me.


What about this alternative program? It works fine.

#include <stdio.h>

main()
{
 char ch;

 getchar();

 printf("Enter the character: ");
 scanf("%c", &ch);
 printf(" You typed: %c\n", ch);
 return 0;
}

Please leave some comments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜