gpt4 book ai didi

c - 从 C 中的文件读取后来自 stdin 的垃圾字符

转载 作者:太空宇宙 更新时间:2023-11-03 23:29:28 25 4
gpt4 key购买 nike

从控制台成功将重定向文件读取到我的程序后,我要求用户输入一个词,然后使用 scanf() 读入该词。

我遇到的问题是 scanf() 立即读取垃圾字符,然后程序继续。它甚至不会暂停让用户在控制台中输入任何内容。当我不打开文件时不会发生这种情况。其他一切都很完美。可能是什么问题:

**我尝试了所有建议,但仍然无法正常工作。我做了一个新项目,就是为了让这部分工作,就在这里。忽略 scanf 只是在寻找一个字符,即使我要求一个词。我这样做只是为了看看程序是否真的会暂停并允许我输入一些东西,但它不会。只需输入一些垃圾,程序就会结束。

 main(){

int n,i;
char ch;
char line[80];

while(fgets(line, 80, stdin) != NULL){
for(i=0;i<80;i++){
ch=line[i];
if(ch=='\n'){
printf("%c",ch);
break;
}
else{
printf("%c",ch);
}
}
}
printf("Please enter a word: ");
scanf("%c",&ch);
}

最佳答案

你不能从一个文件中重定向标准输入,然后还使用键盘进行输入(据我所知)。如果您想这样做,让程序将输入文件作为命令行参数然后像这样运行它会更简单:prog myfile.txt。另外,给自己留一个 fgets() 垫——使用比为 maxlen 分配的数组少一个。如果最大长度不包括“\0”终止字符,则对于需要最大长度的任何内容,对于 C 字符数组使用比分配长度少一的长度总是最安全的。

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

int main(int argc,char *argv[])

{
FILE *f;
int i;
char line[80];

if (argc<2)
{
printf("Usage: %s <inputfile>\n",argv[0]);
exit(10);
}
/* Open file and echo to stdout */
f=fopen(argv[1],"r");
if (f==NULL)
{
printf("Cannot open file %s for input.\n",argv[1]);
exit(20);
}
while (fgets(line, 79, f) != NULL)
printf("%s",line);
fclose(f);

/* Get user input from stdin */
printf("Please enter a word: ");
if (fgets(line,79,stdin)==NULL)
{
printf("Nothing entered. Program aborted.\n");
exit(30);
}
/* Remove CR/LF from end of line */
for (i=strlen(line)-1;i>=0 && (line[i]=='\n' || line[i]=='\r');i--)
;
line[i+1]='\0';
printf("The word entered is: '%s'\n",line);
return(0);
}

关于c - 从 C 中的文件读取后来自 stdin 的垃圾字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19173447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com