Jump to content

Question regarding scanf()

- - - - -

  • Please log in to reply
3 replies to this topic

#1
Muhammad ali

Muhammad ali

    Newbie

  • Members
  • Pip
  • 1 posts
Hi there!!!!!!!!!!!!!!

I was trying to enter character in c using scanf, more thn once but it didnt work:( . I am beginner so plz dont mind if this is a silly question.

here is the code:
#include<stdio.h>

#include<conio.h>

void main()

{

char ch;

do

{

printf("enter y");

scanf("%c",&ch);

}while(ch=='y');

getch();

}

i want the program to continue if y is entered........ but it takes character value only once........
plz tell me what to do.................
I WANT TO DO IT USING SCANF() AND NOT GETCHE().........

thanku

Edited by Roger, 04 December 2011 - 08:34 AM.
added code tags


#2
fread

fread

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 787 posts
You are also reading the line terminating char, which does not evaluate as 'y'.
Perfection of means and confusion of ends seem to characterize our age. Albert Einstein :confused:

#3
alex1

alex1

    Learning Programmer

  • Members
  • PipPipPip
  • 93 posts
why you dont try:

do

{

printf("enter y");

scanf("%c",&ch);

}while((ch!='y')&&(ch!='Y'));



#4
fread

fread

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 787 posts
Taking a page from :this codecall tutorial

If the user does anything other than enter y and hit enter, the loop will terminate. Modify for the behavior you desire.
#include <stdio.h>

int main()
{

    char array[5]; /* one char + '\n' or '\0' */
    char c;

    do
    {
        printf("enter y: ");
        fgets(array,sizeof array, stdin);
    }while (sscanf(array, " % c % c",array,&c) == 2 && !isspace(*array)  && (c == '\n' || c == '\0') && *array == 'y');

}

Perfection of means and confusion of ends seem to characterize our age. Albert Einstein :confused:




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users