C language carriage return and line breaks issue

A carriage (carriage return, '\ r') and line feed (line feed, '\ n')

ASCII value 10 corresponds to the line feed, carriage return ASCII value that corresponds to 13, it is noted that the user presses the Enter key when, for different character input function , different character to read , the code below

 

Test 1:

int main()
{
    char ch;

    ch = getchar();
    printf("%d\n", ch);
}

operation result:

 

Test two:

int main()
{
    char ch;

    ch = getch();
    printf("%d\n", ch);
}

operation result:

 

Test three:

int main()
{
    char ch;

    ch = getche();
    printf("%d\n", ch);
}

operation result:

 

Test Four:

int main()
{
    char ch;

    scanf("%c", &ch);
    printf("%d\n", ch);
}

operation result:

 

As can be seen from the above results, although the inputs are "ENTER" (note the return key is not a carriage return ), but there are differences in the results obtained, be noted that: in the Windows system the ENTER key is treated as \ r \ n is used when we return key input from the keyboard, Windows system will enter key as \ r \ n to process (just different input function to read the results of four character classes above )

getchar-- newline character '\ n' (ASCII value 10)

getch-- carriage return '\ r' (ASCII value 13)

getche-- carriage return '\ r' (ASCII value 13)

scanf——换行符'\n' (ASCII值为10)

回车:使光标移到行首

换行:使光标移到下一行

 

下面再补充下文件操作函数,从文本文件(txt文件)用fscanf_s读取(前提条件:先创建一个txt文件按一下回车键,然后保存)

char ch;
FILE *fp;
errno_t err;

err = fopen_s(&fp, "E:\\ww.txt", "r");
fscanf_s(fp, "%c", &ch, sizeof(ch));

printf("%d\n", ch);

运行效果:

从上面可以看出fscanf_s和scanf对回车键的读取是相同的,都是得到的换行符'\n'(ASCII值为10)

 

使用fgetc读取

int main()
{
    char ch;
    FILE *fp;
    errno_t err;

    err = fopen_s(&fp, "E:\\ww.txt", "r");
    ch = fgetc(fp);
    printf("%d\n", ch);
    if (ch == '\r')
    {
        printf("***");
    }

    return 0;
}

运行结果:

 

从上面的结果可以看出fgetc和fscanf_s读取的字符相同,都是读取到的换行符'\n'(ASCII值为10)

Guess you like

Origin www.linuxidc.com/Linux/2019-08/159762.htm