C编程:字符scanf函数 [英] C programming: character in scanf

查看:110
本文介绍了C编程:字符scanf函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行的程序不要让我输入一个字符一个节目,当我进入整数打印printf和去其他维持其时与问题人物scanf函数......

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;EG的#define 0.23
#定义AG 0.70
TG的#define 0.15主(){
    INT posothta;
    焦炭Eidos公司;
    浮波索;    的printf(Dwse posothta grammatosimwn:);
    scanf函数(%d个,&安培; posothta);
    的printf(Dwse到Eidos公司grammatoshmou:);
    scanf函数(%C,&安培; Eidos公司);    如果(Eidos公司=='E'|| Eidos公司=='E'){
        波索= posothta * EG;
        的printf(为了波索POU plirwnoume欸乃:%F,波索);
    }否则如果(Eidos公司=='A'|| Eidos公司=='A'){
        波索= posothta * AG;
        的printf(为了波索POU plirwnoume欸乃:%F,波索);
    }否则如果(Eidos公司=='T'|| Eidos公司=='T'){
        波索= posothta * TG;
        的printf(为了波索POU plirwnoume欸乃:%F,波索);
    }其他{
        的printf(Kapou exei gine kapoio la9os);
    }    返回0;
}


解决方案

当你做了 scanf()的它采取你问才有价值。例如:

  scanf函数(%d个,&安培; posothta);

比方说,我进入 5 在这里。真的,标准输入有2个字符:'5'的'\\ n'(因为我只好打回车键和生成一个换行符)。

所以到 posothta 那张5,但讨厌的换行符为左坐在那里。接下来的 scanf()的现在正在寻找一个字符,因为换行符(的'\\ n')是的确是一个字符,程序不问问题,它只是拿起了换行,并在移动。

更改code为:

  scanf函数(%C,&安培; Eidos公司);

将跳过告诉 scanf()的说:我希望你能跳过任何空格字符,然后抓住下一个。为了 scanf()的空格字符不仅包括空格,换行,但也。

having problem with scanf character...when running program dont let me enter a character an program when i enter the integer prints the printf and go to last else ...

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

#define EG 0.23
#define AG 0.70
#define TG 0.15

main() {
    int posothta;
    char eidos;
    float poso;

    printf("Dwse posothta grammatosimwn: ");
    scanf("%d",&posothta);
    printf("Dwse to eidos grammatoshmou: ");
    scanf("%c",&eidos);

    if(eidos=='E' || eidos=='e'){
        poso=posothta*EG;
        printf("To poso pou plirwnoume einai: %f",poso);
    }else if(eidos=='A' || eidos=='a'){
        poso=posothta*AG;
        printf("To poso pou plirwnoume einai: %f",poso);
    }else if(eidos=='T' || eidos=='t'){
        poso=posothta*TG;
        printf("To poso pou plirwnoume einai: %f",poso);
    }else{
        printf("Kapou exei gine kapoio la9os");
    }   

    return 0;
}

解决方案

When you do a scanf() it's taking the value you ask for only.. for example:

scanf("%d",&posothta);

Let's say I enter 5 here. Really, stdin got 2 characters: '5' and '\n' (because I had to hit the enter key and that generates a newline character).

So into posothta goes the 5, but that pesky newline is left sitting there. The next scanf() now is looking for a character, and since the newline character ('\n') is indeed a character, the program doesn't ask questions, it simply picks up that newline and moves on.

Change your code to:

scanf(" %c",&eidos);

Will skip tell scanf() that "I want you to skip any whitespace characters, then grab the next one". To scanf() a white space character includes not only spaces, but newlines as well.

这篇关于C编程:字符scanf函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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