Problem with scanf in C

Discussion in 'Programmer's Corner' started by Fraser_Integration, Feb 9, 2010.

  1. Fraser_Integration

    Thread Starter Member

    Nov 28, 2009
    142
    5
    Hi people. I hope my thread title is apt, I've got no idea why the following code won't work. Basically I want to take in 6 floating values and assign 4 in one array and 2 in a second, but they must be entered on one line and then the return key entered at the end. I would've thought that they would've just merrily waited for the six scanf calls to be put in place, but apparently not. If you run the code and type in, say, "1 2 3 4 5 6" then Enter, that is not what you end up with when I check with printf.

    Can anyone see any glaring errors? Cheers.

    Code ( (Unknown Language)):
    1. #include <stdio.h>
    2.  
    3. main()
    4.  
    5. {
    6.  
    7. float A[1][1];
    8. float b[1];
    9. float x1, x2;
    10. int m = 0 , n = 0;
    11.  
    12. printf("Enter 6 values for matrix and answers.\n");
    13.  
    14. for (m=0;m<2;m++)
    15. {
    16.     for(n=0;n<2;n++)
    17.     {              
    18.        scanf("%f", &A[m][n]);
    19.     }
    20. }
    21.  
    22. for (m=0;m<2;m++)
    23. {
    24.     scanf("%f", &b[m]);
    25. }
    26.  
    27. printf("%f   %f   %f   %f  %f  %f ", A[0][0], A[0][1], A[1][0], A[1][1], b[0], b[1]);
    28.  
    29. getchar();getchar();
    30. }
    31.  
    32.  
     
  2. Fraser_Integration

    Thread Starter Member

    Nov 28, 2009
    142
    5
    oh dont worry, I think I probably should've declared the arrays as [2][2] and [2] respectively, even though I only want to input to the [1][1] and [1] element, silly me
     
  3. QuanSai

    New Member

    Feb 14, 2010
    1
    0
    Well, for what you want to do, you could use strtok() to break the input string into tokens. Each token can ten be stored as an element in each array. You could tokenize each floating-point number by indicating in your code that the delimiter is a space. Hence, in the string "12.2 24.4 48.8," token 1 would be 12.2, token 2 would be 24.4, and token 3 would be 48.8. You could then use something like strtod() or atof() to convert each tokenized string to a double. I'm not sure if that matters to you or not though.

    I don't really know how much further you really want me to go with this.
     
Loading...