Asha
Asha

Reputation: 93

What is the best way to scan a float and a double with scanf?

Consider this example:

float a;
double b;

scanf("%f%f", &a, &b);   // A
scanf("%Lf%Lf", &a, &b); // B
scanf("%f%Lf", &a, &b);  // C
scanf("%f%lf", &a, &b);  // D

Upvotes: 3

Views: 38520

Answers (2)

chanchal1987
chanchal1987

Reputation: 2357

You can use

scanf("%f %lf", &a, &b);

scanf type specifiers:

  • c: Single character: Reads the next character. If a width different from 1 is specified, the function reads width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.
  • d: Decimal integer: Number optionally preceded with a + or - sign.
  • e,E,f,g,G: Floating point: Decimal number containing a decimal point, optionally preceded by a + or - sign and optionally folowed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4
  • o: Octal integer.
  • s: String of characters: This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).
  • u: Unsigned decimal integer.
  • x,X: Hexadecimal integer.

Modifiers:

  • h : short int (for d, i and n), or unsigned short int (for o, u and x)
  • l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g)
  • L : long double (for e, f and g)

Source: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

Upvotes: 14

Related Questions