Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Problem with scanf with character in C.

c scanf character

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1 AntonisZaxosWeb

AntonisZaxosWeb

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 04 March 2013 - 10:18 AM

Hello,

I'm not sure why but the program won't let me enter a character:
#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;
	
	
}

Attached Files


Edited by Roger, 04 March 2013 - 03:40 PM.
reformat


#2 PurityLake

PurityLake

    CC Regular

  • Member
  • PipPipPip
  • 36 posts

Posted 04 March 2013 - 10:57 AM

Fixed, you needed to use fflush to empty the buffer since the "\n" character was left in the buffer after getting the input for posothta and the "\n" character was being taking as the input for the char variable eidos.

 

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


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


int main(){

    int posothta;
    char eidos;
    float poso;

    printf("Dwse posothta grammatosimwn: ");
    scanf("%d", &posothta);
    fflush(stdin);
    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;
}

Make sure next time that you enter your code correctly into your posts


Edited by PurityLake, 04 March 2013 - 10:57 AM.





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download