在C中读取新行

时间:2016-06-15 18:32:22

标签: c file input

所以我现在正在尝试逐个字符地读取输入文件,并且我正在尝试查看何时出现新行。我得到的所有字符都很好,但是如果我把它转换为int,我会得到'á'或-97而不是'\ n'代替新行。这是我的代码,我正在使用VS 2015。

int main(void) {
    FILE *fp;
    fp = open_input_file();
    if (fp != 0) {
        char ch = read_character(fp);
        int d = (int)ch;
        while (ch != EOF) {
            printf("%d\n", d);
            ch = read_character(fp);
            d = (int)ch;
        }
    }
    getch();
    return 0;
}
char read_character(FILE *infile) {

    int c;
    c = getc(infile);

    return (char) c;
}

1 个答案:

答案 0 :(得分:0)

您可以检测到对现有代码进行细微更改的换行符:

int main(void) {
    FILE *fp;
    fp = open_input_file();
    if (fp != 0) {
        int ch = read_character(fp);//change to int return (getc() returns int)
        if(ch == '\n') //A simple comparison here will detect newline
        {
            printf("Found Newline: %d\n", ch);
        }
        ///int d = (int)ch;// not necessary with current changes
        while (ch != EOF) {
            //printf("%d\n", d);
            ch = read_character(fp);
            if(ch == '\n')//Note: ASCII for \n is value 10, or hex A
            {
                printf("Found newline: %d\n", ch);
            }

            //d = (int)ch;
        }
    }
    getch();
    return 0;
}

int read_character(FILE *infile) 
{  //changed prototype to return int

    int c;
    c = getc(infile);

    return c;//modified return value to int
}