温馨提示×

getchar在Linux命令行中的实用技巧

小樊
82
2024-09-06 21:22:34
栏目: 智能运维

getchar() 是一个C语言函数,用于从标准输入(通常是键盘)读取一个字符

  1. 使用 getchar() 暂停程序: 在程序中添加 getchar(); 可以使程序暂停,直到用户按下任意键。这在调试或演示时非常有用。
#include<stdio.h>

int main() {
    printf("Press any key to continue...\n");
    getchar();
    printf("Continuing the program...\n");
    return 0;
}
  1. 读取一行文本: 要读取一整行文本,可以使用 fgets() 函数。但如果你想使用 getchar() 读取一行文本,可以这样做:
#include<stdio.h>

int main() {
    char c;
    printf("Enter a line of text: ");
    do {
        c = getchar();
        putchar(c);
    } while (c != '\n');
    return 0;
}
  1. 计算输入字符的数量: 使用 getchar() 可以计算输入字符的数量,包括空格和换行符。
#include<stdio.h>

int main() {
    int count = 0;
    char c;
    printf("Enter some text (press Ctrl+D to end):\n");
    while ((c = getchar()) != EOF) {
        count++;
    }
    printf("You entered %d characters.\n", count);
    return 0;
}
  1. 从文件中读取字符: getchar() 默认从标准输入读取字符,但你可以使用 freopen() 函数将输入重定向到文件。
#include<stdio.h>

int main() {
    FILE *file;
    char c;

    file = freopen("input.txt", "r", stdin);
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    printf("Reading from input.txt:\n");
    while ((c = getchar()) != EOF) {
        putchar(c);
    }

    fclose(stdin);
    return 0;
}

这些只是 getchar() 在 Linux 命令行中的一些实用技巧。在编写C程序时,你可以根据需要使用这些技巧来处理输入和输出。

0