C++ scanf/printf of array

12,176

You are reading double values using the decimal integer format (%d). Try using the double format (%lf) instead...

scanf("%lf,%lf", &A[0], &A[1])
Share:
12,176
Radek Simko
Author by

Radek Simko

Updated on July 16, 2022

Comments

  • Radek Simko
    Radek Simko almost 2 years

    I've written following code:

    int main() {
        double A[2];
        printf("Enter coordinates of the point (x,y):\n");
        scanf("%d,%d", &A[0], &A[1]);
    
        printf("Coordinates of the point: %d, %d", A[0], A[1]);
        return 0;
    }
    

    It's acting like this:

    Enter coordinates of the point (x,y):

    3,5

    Coordinates of the point: 3, 2673912

    How is it possible, that 5 converts into 2673912??

  • dgnorton
    dgnorton over 13 years
    Don't forget printf("Coordinates of the point: %lf, %lf", A[0], A[1]);
  • Radek Simko
    Radek Simko over 13 years
    Thank you, that's it! But it's possible to somehow change the type back to double to be able to operate (+,*,-,/,...) with these numbers? What's the type %lf in fact?
  • Andrew Stein
    Andrew Stein over 13 years
    @Radek A[0] and A[1] are doubles. There is no need to "change the type back to double". +, *, ... will would just fine. %lf, tells scanf that the argument is a "long float", that is, a double. Also note dgnorton's comment on using %lf in the printf
  • user1579701
    user1579701 over 13 years
    %lf just tells scanf that the target variable is a double. So you can do normal operations on those variables after they are read in. Look at the documentation for printf format specifiers for the full range. Are you having another problem?
  • Clifford
    Clifford over 13 years
    @Radek: %lf and %d are format specifiers not types. Nothing is changing type. The specifiers tell the formatted I/O functions what type the arguments are to be interpreted as (because they can otherwise be any type and the function does not know a priori.