INT C =的getchar()? [英] int c = getchar()?

查看:127
本文介绍了INT C =的getchar()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定这样的IM阅读这本书:C程序设计语言 - 通过Kernighan和Ritchie(第二版)和无法理解的事情是如何工作的IM的一个例子

ok so im reading this book: The C Programming Language - By Kernighan and Ritchie (second Edition) and one of the examples im having trouble understanding how things are working.

#include <stdio.h>

#define MAXLINE 1000

int getline(char line[], int maxline);
void copy(char to[], char from[]);

int main(int argc, char *argv[])
{
    int len;

    int max;
    char line[MAXLINE];
    char longest[MAXLINE];

    max = 0;
    while((len = getline(line, MAXLINE)) > 1)
    {
        if(len > max)
        {
            max = len;
            copy(longest, line);
        }
    }
    if(max > 0)
        printf("%s", longest);

    getchar();
    getchar();
    return 0;   
}

int getline(char s[], int lim)
{
    int c, i;

    for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;
    if(c == '\n')
    {
        s[i] = c;
        ++i;     
    }
    s[i] = '\0';

    return i;
}

void copy(char to[], char from[])
{
    int i;

    i = 0;
    while((to[i] = from[i]) != '\0')
        ++i;
}

行:!为(i = 0; I&LT; LIM - 1安培;及(C =的getchar())= EOF和放大器;和C ='\\ n'; ++ I)
它说:C =的getchar(),如何能在命令行整数=字符输入的?整型是的,但如何我键入的字符被存储?

the line : for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) where it says c = getchar(), how can an integer = characters input from the command line? Integers yes but how are the characters i type being stored?

在此先感谢

推荐答案

不像你可能已经使用其他语言,字符用C的的整数。 字符只是另一个整数类型,通常比 INT 8位小,但仍然是一个整数类型。

Unlike some other languages you may have used, chars in C are integers. char is just another integer type, usually 8 bits and smaller than int, but still an integer type.

所以,你不需要 ORD() CHR()中存在的其他语言功能你可能使用。在C语言中你可以间字符和其他整数类型使用强制,或者只是通过分配转换。

So, you don't need ord() and chr() functions that exist in other languages you may have used. In C you can convert between char and other integer types using a cast, or just by assigning.

除非发生EOF,的getchar()定义为返回(的一样的龟etc ),所以如果它可以帮助你能想象它读取一些字符, C ,然后返回(INT)(unsigned char型)C

Unless EOF occurs, getchar() is defined to return "an unsigned char converted to an int" (same as fgetc), so if it helps you can imagine that it reads some char, c, then returns (int)(unsigned char)c.

您可以将这个回一个 unsigned char型只是通过流延或任务,如果你愿意采取理论便携性略有亏损,你可以转换到一个字符用铸造或将其分配到字符

You can convert this back to an unsigned char just by a cast or assignment, and if you're willing to take a slight loss of theoretical portability, you can convert it to a char with a cast or by assigning it to a char.

这篇关于INT C =的getchar()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆