本文介绍了如何从与fgets用C删除多余的字符输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过用gets()函数是C编程不好,它使用与fgets更安全......所以我使用与fgets。不过,我遇到一个问题,与fgets:我进了太多字符,不知何故,它溢出

如何摆脱多余的输入字符?

 字符答案[4];
烧焦ANSWER2 [4];与fgets(答案的sizeof(答案),标准输入);
的printf(答案:%S \\ n,答案);与fgets(ANSWER2,sizeof的(ANSWER2),标准输入);
的printf(ANSWER2:%S \\ n,ANSWER2);

例如,对于首次与fgets,我输入123456,输出我得到的是

 答案:123
ANSWER2:456

我如何从进入下一个与fgets输入取出456?我想进入123456为第一与fgets后,像这样的输出:

 答案:123

然后,用户继续输入的输入为下与fgets ...


解决方案

 与fgets(答案的sizeof(答案),标准输入);
的printf(答案:%S \\ n,答案);
如果(!和strchr(回答,'\\ n'))//换行不存在
    而(龟etc(标准输入)='\\ n'!); //丢弃,直到换行
与fgets(ANSWER2,sizeof的(ANSWER2),标准输入);

I heard using gets() is bad in C programming and it's safer using fgets... So I am using fgets. However, I encounter a problem with fgets: I entered too much characters and somehow, it overflows.

How to get rid of the extra input characters?

char answer[4];
char answer2[4];

fgets(answer,sizeof(answer),stdin);
printf("answer: %s\n",answer);

fgets(answer2,sizeof(answer2),stdin);
printf("answer2: %s\n",answer2);

For example, for the first fgets, I enter 123456, the output I get is

answer: 123
answer2: 456

How do I remove the 456 from going into the next fgets input? I want the output like this after entering 123456 for the 1st fgets:

answer: 123

Then, user continue to enter an input for the next fgets...

解决方案
fgets(answer,sizeof(answer),stdin);
printf("answer: %s\n",answer);
if(!strchr(answer, '\n'))     //newline does not exist
    while(fgetc(stdin)!='\n');//discard until newline
fgets(answer2,sizeof(answer2),stdin);

这篇关于如何从与fgets用C删除多余的字符输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 02:38