程序不执行scanf函数(后得到()),即使使用fflush(标准输入) [英] Program doesn't execute gets() after scanf(), even using fflush(stdin)

查看:267
本文介绍了程序不执行scanf函数(后得到()),即使使用fflush(标准输入)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用scanf()的后浪费太多时间寻找,为什么我的程序没有得到执行()后,我发现了一个解决方案,就是使用后scanf函数fflush(标准输入),(),以使被()得到一个字符串

问题是,fflush(标准输入)不做从中期望是什么:程序继续跳过得到()和我不能写在控制台中的任何短语读

我的code是下一个:

 的#include<&string.h中GT;
#包括LT&;&stdio.h中GT;诠释主(){
    焦农布雷[10];
    烧焦mensaje [80];    的printf(键入您的姓名:\\ n);
    scanf函数(%S,农布雷);    fflush(标准输入);    的printf(现在,键入一条消息:\\ n);
    得到(mensaje);    的printf(3 /%S:%S,农布雷,mensaje);
    返回0;
}


解决方案

如果冲洗STD不工作,然后尝试读取多余的字符和丢弃,所建议的这里

这将工作:

 的#include<&string.h中GT;
#包括LT&;&stdio.h中GT;诠释主(){
    焦农布雷[10];
    烧焦mensaje [80];
    焦炭℃;    的printf(键入您的姓名:\\ n);
    scanf函数(%S,农布雷);    而((C =的getchar())='\\ n'和;!&安培;!C = EOF)
            / * *丢弃/;    的printf(现在,键入一条消息:\\ n);
    得到(mensaje);    的printf(%S:%S,农布雷,mensaje);
    返回0;
}

After wasting too much time searching why my program doesn't execute gets() after using scanf(), I found a solution which is to use fflush(stdin) after scanf() to enable gets() to get a string.

The problem is that fflush(stdin) doesn't do what is expected from it: The program continues skipping gets() and I can't write any phrase in the console to be read.

My code is the next one:

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

int main(){
    char nombre[10];
    char mensaje[80];

    printf("Type your name:\n");
    scanf("%s", nombre);

    fflush(stdin);

    printf("Now, type a message:\n");
    gets(mensaje);

    printf("3/%s:%s",nombre,mensaje);
    return 0;
}

解决方案

If flushing std doesn't work, then try reading in the extra characters and discarding, as suggested here.

This will work:

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

int main(){
    char nombre[10];
    char mensaje[80];
    char c;

    printf("Type your name:\n");
    scanf("%s", nombre);

    while((c= getchar()) != '\n' && c != EOF)
            /* discard */ ;

    printf("Now, type a message:\n");
    gets(mensaje);

    printf("%s:%s",nombre,mensaje);
    return 0;
}

这篇关于程序不执行scanf函数(后得到()),即使使用fflush(标准输入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆