简体   繁体   中英

Weird printf & scanf behavior

I'm pretty new to C programming and I'm wondering why I need to input the same value twice when using the following code?

#include <stdio.h>

int main(void)
{
  int ascii;

  printf("Enter an ASCII value: ");
  scanf(" %d\n", &ascii);
  printf("The %d ASCII code has the character value %c\n", ascii, ascii);

  return 0;
}

You can see that I've had to enter 89 twice in the image below.

http://i.stack.imgur.com/aSEFw.jpg

You need 2 values because the format-string contains two format specifiers , eg:

" The %d ASCII code is character '%c'\n\n"

That specifies two conversion will take place, (eg %d and %c ). They each require a corresponding value in the argument list. eg:

printf ("\n The %d ASCII code is character '%c'\n\n", ascii, ascii);
                ^                           ^           1      2

No magic, just take a close look at man printf . You are simply printing two different conversion for the same value. Therefore, each conversion requires its own value.


If you are still having problems, feel free to ask further. Here is a short version of your code that works fine:

#include <stdio.h>

int main (void) {

    int ascii;
    printf ("Enter and ASCII code value: ");
    if (scanf ("%d%*c", &ascii) != 1) {
        fprintf (stderr, "error: invalid value entered.\n");
        return 1;
    }

    printf ("\n The %d ASCII code is character '%c'\n\n", ascii, ascii);

    return 0;
}

Output

$ ./bin/enterascii
Enter and ASCII code value: 89

 The 89 ASCII code is character 'Y'

Your 'quarts' Post

You do not include the '\\n' in the scanf format string:

scanf(" %d\n", &quarts);

should be something like

scanf("%d%*c", &quarts);

( note: the %*c just reads and discards the '\\n' that results from pressing the Enter key. It is not required, but it is good practice to remove it from the input buffer ( stdin ) or you will be surprised if you attempt to take character or string input with a subsequent scanf call in the same code)

You need to remove the whitespace (the space and \\n ) in your scanf pattern, ie "%d" instead of " %d\\n" .

#include <stdio.h>

int main(void)
{
  int ascii;

  printf("Enter an ASCII value: ");
  scanf("%d", &ascii);
  printf("The %d ASCII code has the character value %c\n", ascii, ascii);

  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM