繁体   English   中英

运行程序时标准输入不起作用

[英]Stdin doesn't work when I run the program

我在 code.c 中有以下 C 代码

int main(int argc, char *argv[]) {
    FILE *openFile = NULL;
    openFile=stdin;
}

但是当我编译并运行我的代码时

gcc -g -o compiledcode code.c
./compiledcode

终端不会提示我输入。 怎么了?

您只是将 stdin 作为文件打开,但不读取文件。 有许多不同的方法可以从 stdin 获取输入。

函数getchar可用于从 stdin 读取单个字符。 使用getc()fgetc()从任意文件流中读取。 例子:

int c = getchar();
printf("you entered %c\n", c);

函数fgets可用于从文件中读取一行。 例子:

char data[200];
fgets(data, sizeof(data), stdin); // we type stdin as file.
printf("you entered %s\n", data);

函数scanf及其函数系列可用于从标准输入读取许多不同的格式。 例子:

char data[200]; // size need be bigger or equal to input length
scanf("%199s", data);  // Protect from buffer overflow
printf("you entered %s\n", data);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM