16

I'm trying to read a character from the console (inside a while loop). But it reads more than once.

Input:

a

Output:

char : a  char : char : '

Code:

while(..)
{
    char in;
    scanf("%c",&in);
}

How can i read only 'a'?

0

5 Answers 5

40
scanf("%c",&in);

leaves a newline which is consumed in the next iteration.

Change it to:

scanf(" %c",&in); // Notice the whitespace in the format string

which tells scanf to ignore whitespaces.

OR

scanf(" %c",&in);
getchar(); // To consume the newline 
Sign up to request clarification or add additional context in comments.

2 Comments

Actually I want to create a char array.Do have an idea about it? (Input size is uncertain).Thanks!
@vkeles: 1) Allocate an array with some initial size, say n using malloc 2) Read chars into the array until the it doesn't exceed n 3) If n chars are read and you want to read more than double the size of the array using realloc. This method is generally followed to avoid calling realloc too frequently. Otherwise, you may do the realloc with your preferred size.
6

To read just one char, use getchar instead:

int c = getchar();
if (c != EOF)
  printf("%c\n", c);

Comments

3

in scanf("%c",&in); you could add a newline character \n after %c in order to absorb the extra characters

scanf("%c\n",&in);

1 Comment

I could not get scanf("%c\n", &in); to work properly. This does work however: scanf(" %[^\n]%*c", &in); The %*c tells scanf to read and discard anything left in the input buffer including newlines. It is always good practice to include a space right after the first " used in scanf. But if you want to preserve the white entered by the user (e.g. spaces before other text is entered), then omit the space following the first " in scanf().
0

you could always use char a = fgetc (stdin);. Unconventional, but works just like getchar().

Comments

-1

you can do like this.

char *ar;
int i=0;
char c;
while((c=getchar()!=EOF)
   ar[i++]=c;
ar[i]='\0';

in this way ,you create a string,but actually it's a char array.

3 Comments

Note that this example doesn't allocate any memory for the character array, nor does it set the initial value of ar, so it will write to an effectively random location in memory, overwriting whatever is there.
Thank you.I really forget to keep the habit to initialize a pointer variable
There is a ) missing after getchar(). And, as @Douglas already mentioned, char ar* should be something like char ar[100], giving the array a size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.