當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C語言 getchar()用法及代碼示例

C 中的 getchar() 函數

getchar() 函數定義在<stdio.h>頭文件。

原型:

    int getchar(void);

參數: FILE *filename(for file handling),否則無效。

返回類型: int

函數的使用:

在文件處理中,我們通過getchar()函數從輸入流中取出字符stdin。這函數原型 getchar()int getchar(void);

讀取的字符是一個無符號字符,它被轉換為一個整數值。在文件處理的情況下,它返回EOF什麽時候文件結束遇到了。如果有錯誤,那麽它也會返回EOF

C 中的 getchar() 示例

#include <stdio.h>
#include <stdlib.h>

int main()
{
    //Initialize the character array
    char str[100];
    int i = 0, j = 0;

    printf("Enter the string into the file\n");
    //takes all the characters until enter is pressed
    while ((str[i] = getchar()) != '\n') {
        //increment the index of the character array
        i++;
    }

    //after taking all the character add null pointer
    //at the end of the string
    str[i] = '\0';
    printf("\nThe file content is - ");
    //loop is break when null pointer is encountered
    while (str[j] != '\0') {
        //print the characters
        putchar(str[j]);
        j++;
    }

    return 0;
}

輸出

getchar() example in C language




相關用法


注:本文由純淨天空篩選整理自Souvik Saha大神的英文原創作品 getchar() function in C language with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。